splashboard 2.10.2

A customizable terminal splash screen with plugin-based data sources
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
#![allow(dead_code)]

use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::layout::{BgLevel, BorderStyle, Child, Flex, Layout, TitleAlign};
use crate::render::RenderSpec;
use crate::theme::ThemeConfig;

const DEFAULT_SETTINGS: &str = include_str!("default_settings.toml");
const DEFAULT_HOME_DASHBOARD: &str = include_str!("default_home_dashboard.toml");
const DEFAULT_PROJECT_DASHBOARD: &str = include_str!("default_project_dashboard.toml");

/// Combined view the runtime consumes: user preferences composed with the active dashboard.
#[derive(Debug, Clone, Default)]
pub struct Config {
    pub general: General,
    pub theme: ThemeConfig,
    pub widgets: Vec<WidgetConfig>,
    pub rows: Vec<RowConfig>,
}

/// User preferences: `[general]` + `[theme]`. Loaded from `$HOME/.splashboard/settings.toml`.
/// Shared across every dashboard the same user sees; per-dir overrides are 0.x out of scope.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SettingsConfig {
    #[serde(default)]
    pub general: General,
    /// Semantic colour overrides. Omitted keys use the built-in defaults; see
    /// [`crate::theme`] for the list of tokens.
    #[serde(default)]
    pub theme: ThemeConfig,
}

/// Widgets + rows. Loaded from one of:
///
/// - a per-dir `./.splashboard/dashboard.toml` or `./.splashboard.toml`
/// - `$HOME/.splashboard/project.dashboard.toml` (CWD == git repo root, no per-dir override)
/// - `$HOME/.splashboard/home.dashboard.toml` (everything else)
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DashboardConfig {
    #[serde(default, rename = "widget")]
    pub widgets: Vec<WidgetConfig>,
    #[serde(default, rename = "row")]
    pub rows: Vec<RowConfig>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct General {
    #[serde(default)]
    pub wait_for_fresh: bool,
    /// Inline viewport height in rows. `None` uses the built-in default. Configs that ship more
    /// widgets than fit in the default bump this to make room.
    #[serde(default)]
    pub height: Option<u16>,
    /// Space reserved around the root layout. `padding = 1` pads one cell on all four sides;
    /// `padding = { x = 2, y = 1 }` splits horizontal / vertical. The viewport bg (if any)
    /// still paints across the whole splash area so the padded band shows the theme colour,
    /// not the terminal background.
    #[serde(default)]
    pub padding: Option<PaddingSpec>,
    /// IANA timezone name (`"Asia/Tokyo"`, `"UTC"`, …) applied to every fetcher and renderer
    /// that emits a human-readable timestamp. Unset (or unrecognised) falls back to the host's
    /// `Local` zone — matching pre-config behaviour. Per-widget options can still override
    /// (for example each `clock_*` widget already carries its own `timezone` knob).
    #[serde(default)]
    pub timezone: Option<String>,
    /// Locale code (`"en_US"`, `"ja_JP"`, …) for chrono's localized month / weekday names.
    /// Requires the `unstable-locales` chrono feature. Unset falls back to `Locale::POSIX`,
    /// which matches chrono's hard-coded English output and keeps unmigrated configs
    /// rendering identical strings.
    #[serde(default)]
    pub locale: Option<String>,
    /// Render the home dashboard automatically on shell startup. Default `true`.
    /// Set to `false` to keep `splashboard` quiet when CWD doesn't resolve to a project,
    /// while still letting the cd-hook paint the project splash on entry.
    #[serde(default = "default_true")]
    pub auto_home: bool,
    /// Run the cd-hook (`splashboard --on-cd`) when entering a project directory. Default
    /// `true`. Set to `false` to disable per-`cd` repaints without unwiring the shell rc.
    #[serde(default = "default_true")]
    pub auto_on_cd: bool,
    /// When the configured dashboard is taller than the terminal viewport, push the
    /// overflowing top rows into shell scrollback (so the user can scroll up to see them)
    /// instead of just clipping with a `… +N rows` hint. Default `false`: the flush path
    /// drags every renderer through ratatui's `insert_before` write loop, which doesn't
    /// honour `Cell::skip` and visibly overdraws stateful image protocols (kitty / iTerm2 /
    /// sixel) in the scrollback portion. Opt in only when the dashboard is text-only and
    /// you specifically want the overflow in scrollback.
    #[serde(default)]
    pub flush_to_scrollback: bool,
}

fn default_true() -> bool {
    true
}

impl Default for General {
    fn default() -> Self {
        Self {
            wait_for_fresh: false,
            height: None,
            padding: None,
            timezone: None,
            locale: None,
            auto_home: true,
            auto_on_cd: true,
            flush_to_scrollback: false,
        }
    }
}

/// Uniform or split padding. Short form `padding = 1` applies the same value to all sides;
/// long form `{ x, y }` sets horizontal (left + right) and vertical (top + bottom) separately.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(untagged)]
pub enum PaddingSpec {
    Uniform(u16),
    Axes {
        #[serde(default)]
        x: u16,
        #[serde(default)]
        y: u16,
    },
}

impl PaddingSpec {
    /// (`x`, `y`) where `x` is left+right-per-side and `y` is top+bottom-per-side.
    pub fn xy(&self) -> (u16, u16) {
        match self {
            Self::Uniform(n) => (*n, *n),
            Self::Axes { x, y } => (*x, *y),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Default)]
pub struct WidgetConfig {
    pub id: String,
    pub fetcher: String,
    /// Renderer selection. `render = "text_plain"` (short form) or
    /// `render = { type = "text_ascii", pixel_size = "quadrant" }` (full form with options).
    /// Absent = pick the default renderer for the fetcher's shape.
    #[serde(default)]
    pub render: Option<RenderSpec>,
    #[serde(default)]
    pub format: Option<String>,
    #[serde(default)]
    pub refresh_interval: Option<u64>,
    /// read_store: file format — "json", "toml", or "text". Other fetchers ignore it.
    #[serde(default)]
    pub file_format: Option<String>,
    /// Fetcher-specific options as a TOML sub-table (`[widget.options]`). Each fetcher
    /// deserializes the keys it cares about; unknown keys are ignored so upgrading the
    /// fetcher never invalidates old configs.
    #[serde(default)]
    pub options: Option<toml::Value>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RowConfig {
    #[serde(default)]
    pub height: Option<SizeSpec>,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub title_align: Option<TitleAlignSpec>,
    #[serde(default)]
    pub border: Option<BorderSpec>,
    /// How children are placed along this row's horizontal axis when they don't fill the row.
    /// `center` is the obvious use case: a narrower widget parked in the middle of its row.
    #[serde(default)]
    pub flex: Option<FlexSpec>,
    /// Which semantic background paints this row. `default` (or omitted) inherits the
    /// viewport bg; `subtle` paints `theme.bg_subtle` — use it to lift header/footer bands
    /// visually off the main content.
    #[serde(default)]
    pub bg: Option<BgSpec>,
    /// Horizontal gap inserted between sibling children, in cells. Sugar for the common
    /// 2/3-column case — `gap = 2` auto-splices empty spacers between children so configs
    /// don't have to declare a `basic_static` "gap" widget just to carve whitespace.
    #[serde(default)]
    pub gap: Option<u16>,
    #[serde(default, rename = "child")]
    pub children: Vec<ChildConfig>,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BgSpec {
    /// Inherit whatever the viewport painted (usually `theme.bg`).
    Default,
    /// Paint `theme.bg_subtle` behind this slot — for header/footer/callout bands.
    Subtle,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FlexSpec {
    Legacy,
    Start,
    Center,
    End,
    SpaceBetween,
    SpaceAround,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChildConfig {
    /// Referenced widget id. Absent means this child is a pure layout spacer — the slot
    /// reserves its `width` but paints nothing. Preferred over the historical
    /// `basic_static`-with-empty-format hack for gap columns. Mutually exclusive with `rows`.
    #[serde(default)]
    pub widget: Option<String>,
    #[serde(default)]
    pub width: Option<SizeSpec>,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub title_align: Option<TitleAlignSpec>,
    #[serde(default)]
    pub border: Option<BorderSpec>,
    /// Per-child background; see [`RowConfig::bg`].
    #[serde(default)]
    pub bg: Option<BgSpec>,
    /// Nested rows stacked vertically inside this child cell. Lets a single cell host a
    /// sub-layout (e.g. uptime above load-avg in the right gutter of a thermometer row).
    /// Mutually exclusive with `widget`; when both are set, `rows` wins.
    #[serde(default, rename = "row")]
    pub rows: Vec<RowConfig>,
}

/// Title alignment on a `border = "top"` (or any bordered) panel. `left` matches ratatui's
/// default; `center` gives `──  title  ──` style section dividers.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TitleAlignSpec {
    Left,
    Center,
    Right,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SizeSpec {
    Fill(u16),
    Length(u16),
    Min(u16),
    Max(u16),
    Percentage(u16),
    /// `height = "auto"` — row / child sizes itself to the rendered content.
    /// Resolves at draw time via the renderer's `natural_height`, so a figlet
    /// hero that word-wraps onto a second block gets the row height it needs
    /// while a single-word hero fits in its natural 7-row box.
    Auto,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum BorderSpec {
    /// No chrome at all — widget fills its full cell, no title drawn. Useful for hero
    /// elements like a big clock that should own its slot without framing.
    None,
    Plain,
    Rounded,
    Thick,
    Double,
    /// Single top edge only, plain style — `border = "top"` + `title = "..."` paints a
    /// section divider above the row. No side or bottom chrome is drawn, so the row keeps
    /// its full inner width for the body beneath the rule.
    Top,
}

impl Config {
    pub fn from_parts(settings: SettingsConfig, dashboard: DashboardConfig) -> Self {
        Self {
            general: settings.general,
            theme: settings.theme,
            widgets: dashboard.widgets,
            rows: dashboard.rows,
        }
    }

    pub fn to_layout(&self) -> Layout {
        Layout::rows(self.rows.iter().map(to_row_child).collect())
    }

    /// Sum of row heights — what the inline viewport needs to be to fit every row without
    /// clipping the bottom. Non-Length sizes fall back to reasonable approximations
    /// (Min/Max use their value, Fill contributes a small default, Percentage is ignored
    /// since it can't resolve without a known viewport).
    pub fn computed_height(&self) -> u16 {
        let rows: u16 = self
            .rows
            .iter()
            .map(|r| row_height_estimate(r.height))
            .sum();
        let pad_y = self
            .general
            .padding
            .map(|p| p.xy().1)
            .unwrap_or(0)
            .saturating_mul(2);
        rows.saturating_add(pad_y)
    }
}

impl SettingsConfig {
    pub fn default_baked() -> Self {
        toml::from_str(DEFAULT_SETTINGS).expect("built-in default settings must parse")
    }

    pub fn parse(toml_str: &str) -> Result<Self, String> {
        toml::from_str(toml_str).map_err(|e| e.to_string())
    }

    /// Loads the user's settings file, or the baked default if it's missing. Errors bubble up
    /// for parse failures so users see what's broken instead of silently getting defaults.
    pub fn load_or_default(path: &Path) -> Result<Self, String> {
        match std::fs::read_to_string(path) {
            Ok(s) => Self::parse(&s).map_err(|e| format!("{}: {e}", path.display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default_baked()),
            Err(e) => Err(format!("{}: {e}", path.display())),
        }
    }
}

impl DashboardConfig {
    pub fn default_home() -> Self {
        toml::from_str(DEFAULT_HOME_DASHBOARD).expect("built-in home dashboard must parse")
    }

    pub fn default_project() -> Self {
        toml::from_str(DEFAULT_PROJECT_DASHBOARD).expect("built-in project dashboard must parse")
    }

    pub fn parse(toml_str: &str) -> Result<Self, String> {
        toml::from_str(toml_str).map_err(|e| e.to_string())
    }
}

/// Where the active dashboard came from. Drives trust gating (local files need explicit trust;
/// the HOME-backed defaults are implicitly trusted) and which baked fallback applies when the
/// file is missing.
#[derive(Debug, Clone)]
pub enum DashboardSource {
    /// Per-dir dashboard discovered in the CWD (`./.splashboard/dashboard.toml` or
    /// `./.splashboard.toml`). Trust-gated.
    Local(PathBuf),
    /// `$HOME/.splashboard/project.dashboard.toml` — used when CWD is a git repo root and no
    /// per-dir dashboard overrides. Baked-in default applies when the file is absent.
    Project,
    /// `$HOME/.splashboard/home.dashboard.toml` — the ambient fallback. Baked-in default
    /// applies when the file is absent.
    Home,
}

pub const LOCAL_DASHBOARD_CANDIDATES: &[&str] =
    &[".splashboard/dashboard.toml", ".splashboard.toml"];

/// Dashboard resolution for a shell-startup render. Returns `Home` as a final fallback so the
/// splash always has something to show.
pub fn resolve_dashboard_source() -> DashboardSource {
    let cwd = std::env::current_dir().ok();
    match cwd.as_deref() {
        Some(c) => resolve_from(c, /* on_cd = */ false).unwrap_or(DashboardSource::Home),
        None => DashboardSource::Home,
    }
}

/// Dashboard resolution for an `--on-cd` render. Returns `None` in the fallback case so the
/// shell hook exits silently instead of repainting the home splash on every `cd`.
pub fn resolve_on_cd_dashboard_source() -> Option<DashboardSource> {
    let cwd = std::env::current_dir().ok()?;
    resolve_from(&cwd, /* on_cd = */ true)
}

/// Nearest project-local dashboard file, for the trust subcommands. Walks up ancestors so
/// running `splashboard trust` from a subdirectory picks the same dashboard the startup
/// resolver would use at the repo root.
pub fn resolve_local_dashboard_path() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    find_local_walking_up(&cwd)
}

fn resolve_from(cwd: &Path, on_cd: bool) -> Option<DashboardSource> {
    if is_home_dir(cwd) {
        // Dotfiles-in-git case: CWD == $HOME still means "home context", not "project".
        return Some(DashboardSource::Home);
    }
    if let Some(path) = find_local_at(cwd) {
        return Some(DashboardSource::Local(path));
    }
    if is_git_repo_root(cwd) {
        return Some(DashboardSource::Project);
    }
    if on_cd {
        None
    } else {
        Some(DashboardSource::Home)
    }
}

fn is_home_dir(path: &Path) -> bool {
    // Respect `HOME` first so the test suite can redirect the home dir on any platform.
    // On Windows, `dirs::home_dir()` consults `SHGetKnownFolderPath(FOLDERID_Profile)` and
    // ignores env vars; checking `HOME` keeps behavior aligned with shells that set it
    // (git-bash, MSYS, WSL, configured PowerShell profiles).
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .or_else(dirs::home_dir);
    let Some(home) = home else {
        return false;
    };
    canonicalize_or(path) == canonicalize_or(&home)
}

fn canonicalize_or(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

fn is_git_repo_root(cwd: &Path) -> bool {
    // "CWD == repo root" using direct `.git` presence. `gix::discover` walks upward, so using
    // it here would misclassify subdirectories as project roots and re-render the project
    // dashboard on every sub-cd. Checking for `.git` right here keeps the rule crisp.
    let dot_git = cwd.join(".git");
    dot_git.is_dir() || dot_git.is_file()
}

fn find_local_walking_up(start: &Path) -> Option<PathBuf> {
    let mut current = Some(start);
    while let Some(dir) = current {
        if let Some(path) = find_local_at(dir) {
            return Some(path);
        }
        current = dir.parent();
    }
    None
}

fn find_local_at(dir: &Path) -> Option<PathBuf> {
    LOCAL_DASHBOARD_CANDIDATES
        .iter()
        .map(|name| dir.join(name))
        .find(|p| p.is_file())
}

fn row_height_estimate(size: Option<SizeSpec>) -> u16 {
    match size {
        Some(SizeSpec::Length(n)) | Some(SizeSpec::Min(n)) | Some(SizeSpec::Max(n)) => n,
        Some(SizeSpec::Fill(_)) => 3,
        Some(SizeSpec::Percentage(_)) => 0,
        // Content-sized rows don't know their height until render, so use the same
        // Fill default estimate used by other flexible sizes for viewport sizing.
        Some(SizeSpec::Auto) => 3,
        None => 3,
    }
}

fn to_row_child(row: &RowConfig) -> Child {
    let cols = intersperse_gaps(row.children.iter().map(to_col_child).collect(), row.gap);
    let mut inner = Layout::cols(cols);
    if let Some(f) = row.flex {
        inner = inner.flexed(to_flex(f));
    }
    let decorated = apply_panel(inner, row.title.as_deref(), row.border, row.title_align);
    let decorated = apply_bg(decorated, row.bg);
    make_child(row.height, decorated)
}

fn intersperse_gaps(children: Vec<Child>, gap: Option<u16>) -> Vec<Child> {
    let Some(n) = gap.filter(|n| *n > 0) else {
        return children;
    };
    let mut out = Vec::with_capacity(children.len() * 2);
    for (i, c) in children.into_iter().enumerate() {
        if i > 0 {
            out.push(Child::length(n, Layout::Empty));
        }
        out.push(c);
    }
    out
}

fn to_flex(f: FlexSpec) -> Flex {
    match f {
        FlexSpec::Legacy => Flex::Legacy,
        FlexSpec::Start => Flex::Start,
        FlexSpec::Center => Flex::Center,
        FlexSpec::End => Flex::End,
        FlexSpec::SpaceBetween => Flex::SpaceBetween,
        FlexSpec::SpaceAround => Flex::SpaceAround,
    }
}

fn to_col_child(c: &ChildConfig) -> Child {
    let leaf = if c.rows.is_empty() {
        match c.widget.as_deref() {
            Some(id) => Layout::widget(id.to_string()),
            None => Layout::Empty,
        }
    } else {
        Layout::rows(c.rows.iter().map(to_row_child).collect())
    };
    let decorated = apply_panel(leaf, c.title.as_deref(), c.border, c.title_align);
    let decorated = apply_bg(decorated, c.bg);
    make_child(c.width, decorated)
}

fn apply_bg(layout: Layout, bg: Option<BgSpec>) -> Layout {
    match bg {
        None | Some(BgSpec::Default) => layout,
        Some(BgSpec::Subtle) => layout.with_bg(BgLevel::Subtle),
    }
}

fn make_child(size: Option<SizeSpec>, layout: Layout) -> Child {
    match size {
        Some(SizeSpec::Fill(w)) => Child::fill(w, layout),
        Some(SizeSpec::Length(n)) => Child::length(n, layout),
        Some(SizeSpec::Min(n)) => Child::min(n, layout),
        Some(SizeSpec::Max(n)) => Child::max(n, layout),
        Some(SizeSpec::Percentage(p)) => Child::percentage(p, layout),
        Some(SizeSpec::Auto) => Child::auto(layout),
        None => Child::fill(1, layout),
    }
}

fn apply_panel(
    layout: Layout,
    title: Option<&str>,
    border: Option<BorderSpec>,
    title_align: Option<TitleAlignSpec>,
) -> Layout {
    // Chrome is opt-in: no border, no panel — even if a title was set. A bare title has no
    // border to render on, so dropping it cleanly is better than pretending. Users who want
    // the framed-with-label look set `border = "rounded"` (or plain/thick/double) explicitly
    // on the widgets that deserve it (charts, tables), keeping hero widgets (clock, greeting)
    // chromeless by default.
    let Some(style) = border.and_then(to_border_style) else {
        return layout;
    };
    let l = match title {
        Some(t) => layout.titled(t).title_aligned(to_title_align(title_align)),
        None => layout,
    };
    l.bordered(style)
}

fn to_title_align(spec: Option<TitleAlignSpec>) -> TitleAlign {
    match spec {
        Some(TitleAlignSpec::Center) => TitleAlign::Center,
        Some(TitleAlignSpec::Right) => TitleAlign::Right,
        Some(TitleAlignSpec::Left) | None => TitleAlign::Left,
    }
}

fn to_border_style(b: BorderSpec) -> Option<BorderStyle> {
    match b {
        BorderSpec::None => None,
        BorderSpec::Plain => Some(BorderStyle::Plain),
        BorderSpec::Rounded => Some(BorderStyle::Rounded),
        BorderSpec::Thick => Some(BorderStyle::Thick),
        BorderSpec::Double => Some(BorderStyle::Double),
        BorderSpec::Top => Some(BorderStyle::Top),
    }
}

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

    #[test]
    fn default_baked_settings_parses() {
        let _ = SettingsConfig::default_baked();
    }

    #[test]
    fn default_home_dashboard_parses() {
        let _ = DashboardConfig::default_home();
    }

    #[test]
    fn default_project_dashboard_parses() {
        let _ = DashboardConfig::default_project();
    }

    #[test]
    fn minimal_dashboard_parses() {
        let toml = r#"
[[widget]]
id = "x"
fetcher = "basic_static"
render = "text_plain"

[[row]]
height = { length = 3 }
[[row.child]]
widget = "x"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        assert_eq!(d.widgets.len(), 1);
        assert_eq!(d.rows.len(), 1);
        assert_eq!(d.rows[0].children.len(), 1);
    }

    #[test]
    fn size_spec_accepts_variants() {
        let toml = r#"
[[widget]]
id = "x"
fetcher = "f"
render = "text_plain"

[[row]]
height = { fill = 2 }
[[row.child]]
widget = "x"
width = { percentage = 50 }

[[row]]
height = { min = 6 }
[[row.child]]
widget = "x"
width = { max = 30 }
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        assert!(matches!(d.rows[0].height, Some(SizeSpec::Fill(2))));
        assert!(matches!(
            d.rows[0].children[0].width,
            Some(SizeSpec::Percentage(50))
        ));
        assert!(matches!(d.rows[1].height, Some(SizeSpec::Min(6))));
        assert!(matches!(
            d.rows[1].children[0].width,
            Some(SizeSpec::Max(30))
        ));
    }

    #[test]
    fn border_spec_parses_all_styles() {
        for name in ["plain", "rounded", "thick", "double", "top"] {
            let toml = format!(
                r#"
[[widget]]
id = "x"
fetcher = "f"
render = "text_plain"

[[row]]
border = "{name}"
[[row.child]]
widget = "x"
"#
            );
            DashboardConfig::parse(&toml).unwrap();
        }
    }

    #[test]
    fn bg_spec_parses_on_row_and_child() {
        let toml = r#"
[[widget]]
id = "x"
fetcher = "basic_static"
render = "text_plain"

[[row]]
bg = "subtle"
height = { length = 2 }
[[row.child]]
widget = "x"
bg = "default"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        assert_eq!(d.rows[0].bg, Some(BgSpec::Subtle));
        assert_eq!(d.rows[0].children[0].bg, Some(BgSpec::Default));
    }

    #[test]
    fn invalid_dashboard_toml_returns_error() {
        let r = DashboardConfig::parse("this is not [valid toml");
        assert!(r.is_err());
    }

    #[test]
    fn missing_settings_file_falls_back_to_default() {
        let path = Path::new("/does/not/exist.toml");
        let s = SettingsConfig::load_or_default(path).unwrap();
        assert!(s.general.height.is_none());
    }

    #[test]
    fn settings_parses_general_and_theme() {
        let toml = r#"
[general]
wait_for_fresh = true
height = 24

[theme]
preset = "nord"
"#;
        let s = SettingsConfig::parse(toml).unwrap();
        assert!(s.general.wait_for_fresh);
        assert_eq!(s.general.height, Some(24));
        assert_eq!(s.theme.preset.as_deref(), Some("nord"));
    }

    #[test]
    fn padding_xy_and_computed_height_cover_size_fallbacks() {
        assert_eq!(PaddingSpec::Uniform(3).xy(), (3, 3));
        assert_eq!(PaddingSpec::Axes { x: 4, y: 2 }.xy(), (4, 2));

        let row = |height| RowConfig {
            height,
            title: None,
            title_align: None,
            border: None,
            flex: None,
            bg: None,
            gap: None,
            children: vec![],
        };
        let config = Config {
            general: General {
                padding: Some(PaddingSpec::Axes { x: 9, y: 2 }),
                ..General::default()
            },
            theme: ThemeConfig::default(),
            widgets: vec![],
            rows: vec![
                row(Some(SizeSpec::Length(4))),
                row(Some(SizeSpec::Min(5))),
                row(Some(SizeSpec::Max(6))),
                row(Some(SizeSpec::Fill(7))),
                row(Some(SizeSpec::Percentage(50))),
                row(Some(SizeSpec::Auto)),
                row(None),
            ],
        };

        assert_eq!(config.computed_height(), 28);
    }

    #[test]
    fn load_or_default_prefixes_non_missing_io_errors() {
        let dir = tempfile::tempdir().unwrap();
        let err = SettingsConfig::load_or_default(dir.path()).unwrap_err();
        assert!(err.starts_with(&format!("{}:", dir.path().display())));
    }

    #[test]
    fn auto_display_toggles_default_to_true() {
        let s = SettingsConfig::default_baked();
        assert!(s.general.auto_home);
        assert!(s.general.auto_on_cd);
    }

    #[test]
    fn auto_display_toggles_parse_when_false() {
        let toml = r#"
[general]
auto_home = false
auto_on_cd = false
"#;
        let s = SettingsConfig::parse(toml).unwrap();
        assert!(!s.general.auto_home);
        assert!(!s.general.auto_on_cd);
    }

    #[test]
    fn auto_display_toggles_partial_override_keeps_other_default() {
        let toml = r#"
[general]
auto_home = false
"#;
        let s = SettingsConfig::parse(toml).unwrap();
        assert!(!s.general.auto_home);
        assert!(s.general.auto_on_cd);
    }

    #[test]
    fn dashboard_ignores_stray_settings_sections() {
        // Dashboard files may end up with leftover `[general]` / `[theme]` blocks after a
        // manual migration. Silently ignore them so the dashboard still parses.
        let toml = r#"
[general]
wait_for_fresh = true

[theme]
preset = "nord"

[[widget]]
id = "x"
fetcher = "basic_static"

[[row]]
[[row.child]]
widget = "x"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        assert_eq!(d.widgets.len(), 1);
        assert_eq!(d.rows.len(), 1);
    }

    #[test]
    fn find_local_picks_up_flat_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join(".splashboard.toml");
        std::fs::write(&file, "").unwrap();
        assert_eq!(find_local_at(dir.path()).unwrap(), file);
    }

    #[test]
    fn find_local_picks_up_directory_form() {
        let dir = tempfile::tempdir().unwrap();
        let subdir = dir.path().join(".splashboard");
        std::fs::create_dir(&subdir).unwrap();
        let file = subdir.join("dashboard.toml");
        std::fs::write(&file, "").unwrap();
        assert_eq!(find_local_at(dir.path()).unwrap(), file);
    }

    #[test]
    fn find_local_prefers_directory_form_when_both_exist() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".splashboard")).unwrap();
        let dir_file = dir.path().join(".splashboard/dashboard.toml");
        std::fs::write(&dir_file, "").unwrap();
        std::fs::write(dir.path().join(".splashboard.toml"), "").unwrap();
        assert_eq!(find_local_at(dir.path()).unwrap(), dir_file);
    }

    #[test]
    fn find_local_walks_up_to_ancestor() {
        let root = tempfile::tempdir().unwrap();
        let file = root.path().join(".splashboard.toml");
        std::fs::write(&file, "").unwrap();
        let nested = root.path().join("a").join("b").join("c");
        std::fs::create_dir_all(&nested).unwrap();
        assert_eq!(find_local_walking_up(&nested).unwrap(), file);
    }

    #[test]
    fn find_local_walking_up_returns_none_when_absent() {
        let dir = tempfile::tempdir().unwrap();
        assert!(find_local_walking_up(dir.path()).is_none());
    }

    #[test]
    fn find_local_at_does_not_walk_up() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join(".splashboard.toml"), "").unwrap();
        let nested = root.path().join("sub");
        std::fs::create_dir(&nested).unwrap();
        assert!(find_local_at(&nested).is_none());
        assert!(find_local_walking_up(&nested).is_some());
    }

    #[test]
    fn resolve_prefers_local_over_project() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".git")).unwrap();
        std::fs::write(dir.path().join(".splashboard.toml"), "").unwrap();
        let src = resolve_from(dir.path(), false).unwrap();
        assert!(matches!(src, DashboardSource::Local(_)));
    }

    #[test]
    fn resolve_picks_project_when_cwd_is_repo_root() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".git")).unwrap();
        let src = resolve_from(dir.path(), false).unwrap();
        assert!(matches!(src, DashboardSource::Project));
    }

    #[test]
    fn resolve_falls_back_to_home_outside_repo() {
        let dir = tempfile::tempdir().unwrap();
        let src = resolve_from(dir.path(), false).unwrap();
        assert!(matches!(src, DashboardSource::Home));
    }

    #[test]
    fn on_cd_silent_in_plain_subdir() {
        let dir = tempfile::tempdir().unwrap();
        assert!(resolve_from(dir.path(), true).is_none());
    }

    #[test]
    fn on_cd_fires_home_at_home_dir() {
        let _lock = crate::paths::TEST_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().unwrap();
        let previous = std::env::var("HOME").ok();
        // SAFETY: scoped mutation of process env; the lock above serializes with other
        // env-touching tests.
        unsafe {
            std::env::set_var("HOME", tmp.path());
        }
        let src = resolve_from(tmp.path(), true).unwrap();
        assert!(matches!(src, DashboardSource::Home));
        unsafe {
            match previous {
                Some(v) => std::env::set_var("HOME", v),
                None => std::env::remove_var("HOME"),
            }
        }
    }

    #[test]
    fn on_cd_fires_at_repo_root() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".git")).unwrap();
        let src = resolve_from(dir.path(), true).unwrap();
        assert!(matches!(src, DashboardSource::Project));
    }

    #[test]
    fn on_cd_silent_in_repo_subdir() {
        let root = tempfile::tempdir().unwrap();
        std::fs::create_dir(root.path().join(".git")).unwrap();
        let sub = root.path().join("src");
        std::fs::create_dir(&sub).unwrap();
        // Sub-directory: even though an ancestor is a git root, `resolve_from` must not walk
        // up — that's what keeps cd into src/ from re-triggering the project splash.
        assert!(resolve_from(&sub, true).is_none());
    }

    #[test]
    fn child_without_widget_is_layout_spacer() {
        // `[[row.child]]` with no `widget = ...` is a pure layout spacer — it reserves its
        // `width` but renders nothing. Replaces the historical `basic_static` gap hack.
        let toml = r#"
[[widget]]
id = "a"
fetcher = "basic_static"
render = "text_plain"

[[row]]
height = { length = 3 }
[[row.child]]
width = { length = 2 }
[[row.child]]
widget = "a"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        assert!(d.rows[0].children[0].widget.is_none());
        let layout = Config::from_parts(SettingsConfig::default(), d).to_layout();
        let cols = match layout {
            Layout::Stack { children, .. } => match &children[0].layout {
                Layout::Stack { children: cs, .. } => cs.clone(),
                _ => panic!("expected inner cols stack"),
            },
            _ => panic!("expected rows at root"),
        };
        assert!(matches!(cols[0].layout, Layout::Empty));
        assert!(matches!(cols[1].layout, Layout::Widget { .. }));
    }

    #[test]
    fn row_gap_splices_spacers_between_children() {
        let toml = r#"
[[widget]]
id = "a"
fetcher = "basic_static"
render = "text_plain"

[[widget]]
id = "b"
fetcher = "basic_static"
render = "text_plain"

[[row]]
height = { length = 3 }
gap = 2
[[row.child]]
widget = "a"
[[row.child]]
widget = "b"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        assert_eq!(d.rows[0].gap, Some(2));
        let layout = Config::from_parts(SettingsConfig::default(), d).to_layout();
        let cols = match layout {
            Layout::Stack { children, .. } => match &children[0].layout {
                Layout::Stack { children: cs, .. } => cs.clone(),
                _ => panic!("expected inner cols stack"),
            },
            _ => panic!("expected rows at root"),
        };
        assert_eq!(cols.len(), 3);
        assert!(matches!(cols[0].layout, Layout::Widget { .. }));
        assert!(matches!(cols[1].layout, Layout::Empty));
        assert!(matches!(cols[2].layout, Layout::Widget { .. }));
        assert!(matches!(cols[1].size, crate::layout::Size::Length(2)));
    }

    #[test]
    fn row_gap_zero_is_noop() {
        let toml = r#"
[[widget]]
id = "a"
fetcher = "basic_static"

[[row]]
gap = 0
[[row.child]]
widget = "a"
[[row.child]]
widget = "a"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        let layout = Config::from_parts(SettingsConfig::default(), d).to_layout();
        let cols = match layout {
            Layout::Stack { children, .. } => match &children[0].layout {
                Layout::Stack { children: cs, .. } => cs.clone(),
                _ => panic!(),
            },
            _ => panic!(),
        };
        assert_eq!(cols.len(), 2);
    }

    #[test]
    fn helper_mappings_cover_sizes_flex_titles_and_borders() {
        assert_eq!(to_flex(FlexSpec::Legacy), Flex::Legacy);
        assert_eq!(to_flex(FlexSpec::Start), Flex::Start);
        assert_eq!(to_flex(FlexSpec::Center), Flex::Center);
        assert_eq!(to_flex(FlexSpec::End), Flex::End);
        assert_eq!(to_flex(FlexSpec::SpaceBetween), Flex::SpaceBetween);
        assert_eq!(to_flex(FlexSpec::SpaceAround), Flex::SpaceAround);

        assert_eq!(
            to_title_align(Some(TitleAlignSpec::Center)),
            TitleAlign::Center
        );
        assert_eq!(
            to_title_align(Some(TitleAlignSpec::Right)),
            TitleAlign::Right
        );
        assert_eq!(to_title_align(Some(TitleAlignSpec::Left)), TitleAlign::Left);
        assert_eq!(to_title_align(None), TitleAlign::Left);

        assert_eq!(to_border_style(BorderSpec::None), None);
        assert_eq!(to_border_style(BorderSpec::Plain), Some(BorderStyle::Plain));
        assert_eq!(
            to_border_style(BorderSpec::Rounded),
            Some(BorderStyle::Rounded)
        );
        assert_eq!(to_border_style(BorderSpec::Thick), Some(BorderStyle::Thick));
        assert_eq!(
            to_border_style(BorderSpec::Double),
            Some(BorderStyle::Double)
        );
        assert_eq!(to_border_style(BorderSpec::Top), Some(BorderStyle::Top));

        assert_eq!(
            make_child(Some(SizeSpec::Fill(2)), Layout::Empty).size,
            Size::Fill(2)
        );
        assert_eq!(
            make_child(Some(SizeSpec::Length(3)), Layout::Empty).size,
            Size::Length(3)
        );
        assert_eq!(
            make_child(Some(SizeSpec::Min(4)), Layout::Empty).size,
            Size::Min(4)
        );
        assert_eq!(
            make_child(Some(SizeSpec::Max(5)), Layout::Empty).size,
            Size::Max(5)
        );
        assert_eq!(
            make_child(Some(SizeSpec::Percentage(60)), Layout::Empty).size,
            Size::Percentage(60)
        );
        assert_eq!(
            make_child(Some(SizeSpec::Auto), Layout::Empty).size,
            Size::Auto
        );
        assert_eq!(make_child(None, Layout::Empty).size, Size::Fill(1));
    }

    #[test]
    fn panel_and_git_root_helpers_cover_remaining_branches() {
        let titled = apply_panel(
            Layout::widget("hero"),
            Some("Status"),
            Some(BorderSpec::Top),
            Some(TitleAlignSpec::Right),
        );
        let Layout::Widget {
            panel: Some(panel), ..
        } = titled
        else {
            panic!("expected widget with panel");
        };
        assert_eq!(panel.title.as_deref(), Some("Status"));
        assert_eq!(panel.border, BorderStyle::Top);
        assert_eq!(panel.title_align, TitleAlign::Right);

        let untitled = apply_panel(
            Layout::widget("chart"),
            None,
            Some(BorderSpec::Rounded),
            Some(TitleAlignSpec::Center),
        );
        let Layout::Widget {
            panel: Some(panel), ..
        } = untitled
        else {
            panic!("expected rounded widget panel");
        };
        assert!(panel.title.is_none());
        assert_eq!(panel.border, BorderStyle::Rounded);
        assert_eq!(panel.title_align, TitleAlign::Left);

        let chromeless = apply_panel(
            Layout::widget("clock"),
            Some("Ignored"),
            Some(BorderSpec::None),
            Some(TitleAlignSpec::Center),
        );
        assert!(matches!(chromeless, Layout::Widget { panel: None, .. }));

        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".git"), "gitdir: ../.git/worktrees/x").unwrap();
        assert!(is_git_repo_root(dir.path()));
        assert_eq!(
            canonicalize_or(&dir.path().join("missing")),
            dir.path().join("missing")
        );
    }

    #[test]
    fn to_layout_builds_nested_rows_of_cols() {
        let toml = r#"
[[widget]]
id = "a"
fetcher = "basic_static"
render = "text_plain"

[[widget]]
id = "b"
fetcher = "basic_static"
render = "text_plain"

[[row]]
height = { length = 3 }
[[row.child]]
widget = "a"
[[row.child]]
widget = "b"
"#;
        let d = DashboardConfig::parse(toml).unwrap();
        let config = Config::from_parts(SettingsConfig::default(), d);
        let layout = config.to_layout();
        match layout {
            Layout::Stack { children, .. } => {
                assert!(!children.is_empty());
            }
            _ => panic!("expected Stack at root"),
        }
    }
}