mirador 0.0.0

A personal information dashboard for your terminal: world clocks, weather, tasks, and live system metrics.
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
//! Configuration loading.
//!
//! Mirador reads a single TOML file. On first run, if no file exists, a fully
//! commented default is written to disk so there is always something to edit.
//!
//! Resolution order for the config path:
//! 1. `--config <PATH>` on the command line
//! 2. `$MIRADOR_CONFIG`
//! 3. `$XDG_CONFIG_HOME/mirador/config.toml` (or the platform equivalent)

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

use anyhow::{Context, Result};
use serde::Deserialize;

use crate::theme::Theme;

/// The default config written on first run.
pub const DEFAULT_CONFIG: &str = include_str!("../assets/default_config.toml");

/// Top-level configuration.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    pub general: General,
    pub theme: Theme,
    pub layout: Layout,
    pub clocks: ClocksConfig,
    pub weather: WeatherConfig,
    pub todo: TodoConfig,
    pub notes: NotesConfig,
    pub stocks: StocksConfig,
    pub calendar: CalendarConfig,
    pub cpu: CpuConfig,
    pub network: NetworkConfig,
}

/// Global behaviour.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct General {
    /// Frame budget in milliseconds. Lower is smoother and burns more CPU.
    pub tick_rate_ms: u64,
    /// Draw a border around each panel.
    pub show_borders: bool,
    /// Show the key-hint line at the bottom of the screen.
    pub show_status_bar: bool,
    /// Report mouse clicks and scrolling to the dashboard.
    ///
    /// This is a genuine trade: while mirador holds the mouse, the terminal's
    /// own click-to-select-text stops working, and copying a value off the
    /// dashboard needs the terminal's override modifier (Shift in most, Option
    /// in macOS Terminal and iTerm2). Set to `false` to keep selection.
    pub mouse: bool,
}

impl Default for General {
    fn default() -> Self {
        Self {
            tick_rate_ms: 250,
            show_borders: true,
            show_status_bar: true,
            mouse: true,
        }
    }
}

/// A grid of rows, each holding one or more side-by-side panels.
///
/// `height` and `width` are relative weights, not absolute cells, so a layout
/// keeps its proportions at any terminal size.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Layout {
    pub rows: Vec<LayoutRow>,
}

impl Default for Layout {
    fn default() -> Self {
        Self {
            rows: vec![
                LayoutRow {
                    height: 30,
                    panels: vec![
                        LayoutPanel {
                            widget: "clocks".into(),
                            width: 40,
                        },
                        LayoutPanel {
                            widget: "weather".into(),
                            width: 60,
                        },
                    ],
                },
                LayoutRow {
                    height: 45,
                    panels: vec![LayoutPanel {
                        widget: "todo".into(),
                        width: 100,
                    }],
                },
                LayoutRow {
                    height: 25,
                    panels: vec![
                        LayoutPanel {
                            widget: "cpu".into(),
                            width: 50,
                        },
                        LayoutPanel {
                            widget: "network".into(),
                            width: 50,
                        },
                    ],
                },
            ],
        }
    }
}

/// One horizontal band of the dashboard.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LayoutRow {
    /// Relative height weight.
    pub height: u16,
    pub panels: Vec<LayoutPanel>,
}

impl Default for LayoutRow {
    fn default() -> Self {
        Self {
            height: 1,
            panels: Vec::new(),
        }
    }
}

/// One panel within a row.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LayoutPanel {
    /// Widget id: `clocks`, `weather`, `todo`, `cpu` or `network`.
    pub widget: String,
    /// Relative width weight.
    pub width: u16,
}

impl Default for LayoutPanel {
    fn default() -> Self {
        Self {
            widget: String::new(),
            width: 1,
        }
    }
}

/// World clock settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ClocksConfig {
    /// Clocks to display, in order.
    pub zones: Vec<ClockZone>,
    /// `strftime`-style time format.
    pub time_format: String,
    /// `strftime`-style date format. Empty hides the date.
    pub date_format: String,
    /// Show each zone's offset relative to the primary clock.
    pub show_offset: bool,
    /// Include seconds in the large clock. Off by default: a ticking seconds
    /// field draws the eye every second, which is the opposite of what a
    /// leave-it-running dashboard wants.
    pub show_seconds: bool,
}

impl Default for ClocksConfig {
    fn default() -> Self {
        Self {
            zones: vec![
                ClockZone {
                    label: "Local".into(),
                    timezone: "local".into(),
                },
                ClockZone {
                    label: "UTC".into(),
                    timezone: "UTC".into(),
                },
                ClockZone {
                    label: "London".into(),
                    timezone: "Europe/London".into(),
                },
                ClockZone {
                    label: "Tokyo".into(),
                    timezone: "Asia/Tokyo".into(),
                },
            ],
            time_format: "%H:%M:%S".into(),
            date_format: "%A %d %B".into(),
            show_offset: true,
            show_seconds: true,
        }
    }
}

/// A single clock.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct ClockZone {
    /// Display name.
    pub label: String,
    /// IANA timezone id, or the literal `local` for the system zone.
    pub timezone: String,
}

/// Weather settings. Data comes from Open-Meteo, which needs no API key.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WeatherConfig {
    /// Place name, geocoded on startup when `latitude`/`longitude` are unset.
    pub location: String,
    /// Explicit latitude; skips geocoding.
    pub latitude: Option<f64>,
    /// Explicit longitude; skips geocoding.
    pub longitude: Option<f64>,
    /// `metric` (C, km/h) or `imperial` (F, mph).
    pub units: String,
    /// Number of forecast hours to show, 1 to 24.
    pub forecast_hours: u8,
    /// Minutes between refreshes.
    pub refresh_minutes: u64,
}

impl Default for WeatherConfig {
    fn default() -> Self {
        Self {
            location: "Boston, Massachusetts".into(),
            latitude: None,
            longitude: None,
            units: "imperial".into(),
            forecast_hours: 8,
            refresh_minutes: 30,
        }
    }
}

/// To-do list settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TodoConfig {
    /// Path to the task file. `~` is expanded. Defaults to the data directory.
    pub file: Option<PathBuf>,
    /// Show completed tasks in the list.
    pub show_completed: bool,
    /// Initial sort: `smart`, `due`, `priority`, `created` or `title`.
    pub sort: String,
    /// Date format used in the list.
    pub date_format: String,
    /// Hide tasks whose due date is more than this many days out. 0 disables.
    pub horizon_days: u32,
}

impl Default for TodoConfig {
    fn default() -> Self {
        Self {
            file: None,
            show_completed: false,
            sort: "smart".into(),
            date_format: "%a %d %b".into(),
            horizon_days: 0,
        }
    }
}

/// Stock watchlist settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StocksConfig {
    /// Symbols used to seed the watchlist on first run only. After that the
    /// watchlist file is the truth, so symbols added or removed in the UI stick.
    pub symbols: Vec<String>,
    /// Path to the watchlist file. `~` is expanded. Defaults to the data
    /// directory. Only symbols are stored; prices are never written to disk.
    pub file: Option<PathBuf>,
    /// Where quotes come from. See `[stocks].source` in the default config.
    pub source: String,
    /// Seconds between polls. Clamped to a minimum of 60: the sources are free
    /// and unauthenticated, and hammering them gets the address blocked.
    pub refresh_secs: u64,
    /// Milliseconds between individual symbol requests, so a watchlist goes out
    /// as a trickle rather than a burst.
    pub stagger_ms: u64,
    /// Draw the intraday sparkline when the panel is wide enough for it.
    pub show_sparkline: bool,
}

impl Default for StocksConfig {
    fn default() -> Self {
        Self {
            symbols: vec!["AAPL".into(), "MSFT".into(), "^GSPC".into()],
            file: None,
            source: "yahoo".to_string(),
            refresh_secs: 120,
            stagger_ms: 400,
            show_sparkline: true,
        }
    }
}

/// Notes settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NotesConfig {
    /// Path to the notes file. `~` is expanded. Defaults to the data directory.
    pub file: Option<PathBuf>,
    /// Date format used in the list.
    pub date_format: String,
    /// Where the note body sits: `below` the list, or `beside` it.
    ///
    /// Below by default. Beside splits a finite width between two things that
    /// both want it — the list loses room for titles and the body loses room
    /// for prose — where stacking gives each the full width and trades only
    /// height, which is the cheaper axis for both.
    pub preview: String,
}

impl Default for NotesConfig {
    fn default() -> Self {
        Self {
            file: None,
            date_format: "%d %b".to_string(),
            preview: "below".to_string(),
        }
    }
}

/// Calendar settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CalendarConfig {
    /// How many months to show, starting with the current one. The panel draws
    /// as many as its size allows, up to this number.
    pub months: u8,
    /// `sunday` or `monday`.
    pub week_starts: String,
}

impl Default for CalendarConfig {
    fn default() -> Self {
        Self {
            months: 2,
            week_starts: "sunday".to_string(),
        }
    }
}

/// CPU chart settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CpuConfig {
    /// Number of samples retained in the moving chart.
    pub history: usize,
    /// Seconds between samples.
    pub sample_secs: u64,
    /// Also draw a per-core breakdown when the panel is tall enough.
    pub show_per_core: bool,
    /// Percentage above which the readout turns the warning colour.
    pub warn_pct: f32,
    /// Percentage above which the readout turns the error colour.
    pub critical_pct: f32,
}

impl Default for CpuConfig {
    fn default() -> Self {
        Self {
            history: 120,
            sample_secs: 1,
            show_per_core: true,
            warn_pct: 70.0,
            critical_pct: 90.0,
        }
    }
}

/// Network chart settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NetworkConfig {
    /// Interfaces to include. Empty means every non-loopback interface.
    pub interfaces: Vec<String>,
    /// Number of samples retained in the moving chart.
    pub history: usize,
    /// Seconds between samples.
    pub sample_secs: u64,
}

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            interfaces: Vec::new(),
            history: 120,
            sample_secs: 1,
        }
    }
}

impl Config {
    /// Load the config, creating a commented default if none exists.
    pub fn load(explicit: Option<PathBuf>) -> Result<(Self, PathBuf)> {
        let path = match explicit {
            Some(p) => p,
            None => Self::default_path()?,
        };

        if !path.exists() {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("creating config directory {}", parent.display()))?;
            }
            std::fs::write(&path, DEFAULT_CONFIG)
                .with_context(|| format!("writing default config to {}", path.display()))?;
        }

        let raw = std::fs::read_to_string(&path)
            .with_context(|| format!("reading config {}", path.display()))?;
        let config: Self = toml::from_str(&raw).map_err(|e| stale_config_hint(&e, &path))?;
        config.validate()?;
        Ok((config, path))
    }

    /// Platform-appropriate config location.
    pub fn default_path() -> Result<PathBuf> {
        if let Ok(from_env) = std::env::var("MIRADOR_CONFIG") {
            return Ok(PathBuf::from(from_env));
        }
        let dir = dirs::config_dir()
            .context("could not determine a config directory for this platform")?;
        Ok(dir.join("mirador").join("config.toml"))
    }

    /// Where task data lives when `[todo].file` is unset.
    pub fn default_data_path() -> Result<PathBuf> {
        Ok(Self::default_data_dir()?.join("todos.toml"))
    }

    /// Platform data directory for mirador's own files.
    fn default_data_dir() -> Result<PathBuf> {
        let dir =
            dirs::data_dir().context("could not determine a data directory for this platform")?;
        Ok(dir.join("mirador"))
    }

    /// Reject configs that would produce an unusable dashboard, with a message
    /// that says how to fix it rather than just what is wrong.
    fn validate(&self) -> Result<()> {
        if self.layout.rows.is_empty() {
            anyhow::bail!(
                "`[layout]` has no rows, so there is nothing to draw. \
                 Add at least one `{{ height = 100, panels = [...] }}` entry to `rows`."
            );
        }
        for row in &self.layout.rows {
            if row.panels.is_empty() {
                anyhow::bail!(
                    "a layout row has an empty `panels` list. \
                     Remove the row, or give it a panel such as \
                     `{{ widget = \"todo\", width = 100 }}`."
                );
            }
            for panel in &row.panels {
                if !crate::widgets::is_known_widget(&panel.widget) {
                    anyhow::bail!(
                        "unknown widget `{}`. Available widgets: {}.",
                        panel.widget,
                        crate::widgets::WIDGET_NAMES.join(", ")
                    );
                }
            }
        }
        if !matches!(self.weather.units.as_str(), "metric" | "imperial") {
            anyhow::bail!(
                "`[weather].units` is `{}`; expected `metric` or `imperial`.",
                self.weather.units
            );
        }
        Ok(())
    }

    /// Resolve the task file path, expanding a leading `~`.
    pub fn todo_path(&self) -> Result<PathBuf> {
        match &self.todo.file {
            Some(p) => Ok(expand_tilde(p)),
            None => Self::default_data_path(),
        }
    }

    /// Resolve the notes file path, expanding a leading `~`.
    pub fn notes_path(&self) -> Result<PathBuf> {
        match &self.notes.file {
            Some(p) => Ok(expand_tilde(p)),
            None => Ok(Self::default_data_dir()?.join("notes.toml")),
        }
    }

    /// Resolve the watchlist file path, expanding a leading `~`.
    pub fn stocks_path(&self) -> Result<PathBuf> {
        match &self.stocks.file {
            Some(p) => Ok(expand_tilde(p)),
            None => Ok(Self::default_data_dir()?.join("watchlist.toml")),
        }
    }
}

/// Turn a parse failure into an error that says how to fix it.
///
/// The common case by far is a config written by an older version: mirador
/// creates the file once and never rewrites it, so a key that has since been
/// renamed sits there looking correct. Silently ignoring such a key is worse
/// than failing on it — it makes a stale config look like stale code, and
/// sends people hunting through git for a build that was never the problem.
fn stale_config_hint(error: &toml::de::Error, path: &Path) -> anyhow::Error {
    // Keys renamed since 0.1.0, and what replaced them.
    const RENAMED: &[(&str, &str)] = &[
        (
            "forecast_days",
            "`forecast_hours` — the forecast is hourly now",
        ),
        ("rx", "the `[theme.rx_gradient]` table"),
        ("tx", "the `[theme.tx_gradient]` table"),
    ];

    let message = error.to_string();

    for (old, replacement) in RENAMED {
        if message.contains(&format!("`{old}`")) {
            return anyhow::anyhow!(
                "{message}\n\nThe config at {} was written by an older version \
                 of mirador: `{old}` was replaced by {replacement}.\n\nRun \
                 `mirador --migrate-config` to update it in place; your original \
                 is kept as a .bak file.",
                path.display(),
            );
        }
    }

    anyhow::anyhow!(
        "{message}\n\nin {}. Run `mirador --print-config` to see the current format.",
        path.display()
    )
}

/// Expand a leading `~` to the user's home directory.
fn expand_tilde(path: &Path) -> PathBuf {
    let Ok(stripped) = path.strip_prefix("~") else {
        return path.to_path_buf();
    };
    dirs::home_dir().map_or_else(|| path.to_path_buf(), |home| home.join(stripped))
}

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

    #[test]
    fn shipped_default_config_parses() {
        let config: Config =
            toml::from_str(DEFAULT_CONFIG).expect("the bundled default config must always parse");
        config
            .validate()
            .expect("the bundled default config must always validate");
    }

    #[test]
    fn empty_config_falls_back_to_defaults() {
        let config: Config = toml::from_str("").expect("an empty config is valid");
        assert_eq!(config.layout.rows.len(), 3);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn unknown_widget_is_rejected_with_a_helpful_message() {
        let config: Config =
            toml::from_str("[layout]\nrows = [{ height = 1, panels = [{ widget = \"nope\" }] }]")
                .expect("parses");
        let err = config.validate().expect_err("must be rejected");
        let msg = err.to_string();
        assert!(msg.contains("unknown widget `nope`"), "got: {msg}");
        assert!(
            msg.contains("todo"),
            "should list valid widgets, got: {msg}"
        );
    }

    #[test]
    fn a_key_from_an_older_version_is_rejected_with_a_migration_hint() {
        // The exact failure that made a current build look like an old one.
        let err = toml::from_str::<Config>("[weather]\nforecast_days = 4")
            .map_err(|e| stale_config_hint(&e, Path::new("/tmp/config.toml")))
            .expect_err("a removed key must not be silently ignored");
        let message = format!("{err:#}");
        assert!(message.contains("forecast_days"), "got: {message}");
        assert!(message.contains("forecast_hours"), "got: {message}");
    }

    #[test]
    fn an_unrecognised_key_names_itself_rather_than_being_ignored() {
        let err = toml::from_str::<Config>("[weather]\nwibble = 4")
            .map_err(|e| stale_config_hint(&e, Path::new("/tmp/config.toml")))
            .expect_err("typos must be reported");
        assert!(format!("{err:#}").contains("wibble"));
    }

    #[test]
    fn bad_units_are_rejected() {
        let config: Config = toml::from_str("[weather]\nunits = \"kelvin\"").expect("parses");
        assert!(config.validate().is_err());
    }

    #[test]
    fn bad_colour_names_are_rejected_at_parse_time() {
        let err = toml::from_str::<Config>("[theme]\naccent = \"chartreuse\"")
            .expect_err("must be rejected");
        assert!(err.to_string().contains("not a colour"), "got: {err}");
    }

    #[test]
    fn tilde_expands_to_home() {
        if let Some(home) = dirs::home_dir() {
            assert_eq!(expand_tilde(Path::new("~/x.toml")), home.join("x.toml"));
        }
        assert_eq!(expand_tilde(Path::new("/abs/x")), PathBuf::from("/abs/x"));
    }
}