mirador 0.16.0

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
//! Moving a panel around the grid.
//!
//! Split out from [`crate::app`] because the interesting part is arithmetic on
//! a [`Layout`] and nothing else — no terminal, no panels, no config file — so
//! it can be tested by moving a panel and looking at where it went.
//!
//! Two rules shape all of it. **Widths travel with the panel**, so a panel you
//! sized stays the size you made it rather than inheriting whatever the slot it
//! landed in happened to be. And **the weights always sum to what they summed
//! to before**, so a row you tuned is never quietly rescaled by a move
//! somewhere else on the dashboard.

use crate::config::{Layout, LayoutRow};

/// Which way a panel was asked to go.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    Left,
    Right,
    Up,
    Down,
}

/// Move the panel at `(row, column)`, returning where it ended up.
///
/// `None` means the move was refused and the layout is untouched — the panel is
/// already against the edge it was pushed at, and has nowhere further to go.
pub fn move_panel(
    layout: &mut Layout,
    row: usize,
    column: usize,
    direction: Direction,
) -> Option<(usize, usize)> {
    if column >= layout.rows.get(row)?.panels.len() {
        return None;
    }
    match direction {
        Direction::Left | Direction::Right => {
            let entry = layout.rows.get_mut(row)?;
            let target = if direction == Direction::Left {
                column.checked_sub(1)?
            } else {
                (column + 1 < entry.panels.len()).then_some(column + 1)?
            };
            // Swapping the whole entry rather than the two widget names is what
            // makes the width travel: swapping names would leave the panel in a
            // slot sized for its neighbour.
            entry.panels.swap(column, target);
            Some((row, target))
        }
        Direction::Up | Direction::Down => {
            vertical(layout, row, column, direction == Direction::Down)
        }
    }
}

/// Move a panel to the row above or below, or off the edge into a row of its
/// own.
fn vertical(layout: &mut Layout, row: usize, column: usize, down: bool) -> Option<(usize, usize)> {
    let alone = layout.rows[row].panels.len() == 1;
    let off_the_end = if down {
        row + 1 >= layout.rows.len()
    } else {
        row == 0
    };

    if off_the_end {
        // A panel that already has a row to itself has nowhere to go: giving it
        // another one would be a move that changes nothing, repeated for as
        // long as the key is held.
        return (!alone).then(|| promote(layout, row, column, down))?;
    }

    let target = if down { row + 1 } else { row - 1 };

    // Land where the panel already looks like it is, rather than at the same
    // index. The rows hold different numbers of panels, so the rightmost of
    // three moved down into a row of four belongs on the right, not at index 2.
    let centre = centre_of(&layout.rows[row], column);
    let at = insertion_point(&layout.rows[target], centre);

    let panel = layout.rows[row].panels.remove(column);
    layout.rows[target].panels.insert(at, panel);

    Some((close_if_empty(layout, row, target), at))
}

/// Give the panel a row of its own at the outer edge.
fn promote(layout: &mut Layout, row: usize, column: usize, below: bool) -> Option<(usize, usize)> {
    // Splitting a weight of one in two needs finer granularity than the layout
    // currently has. Scale every row rather than inventing weight for this one:
    // doubling preserves every proportion exactly, which is what the rule at the
    // top of this module is actually about.
    //
    // It used to read `source.height.max(2)`, which for a row of height 1 handed
    // out two rows of 1 and grew the total by one. A `[[layout.rows]]` written
    // without a `height` gets `LayoutRow::default()`, which is height 1, and
    // nothing validates heights — so with rows of `[1, 1]` a promotion turned a
    // 50/50 dashboard into 33/33/33 and rescaled a row the user had not touched.
    // `a_move_never_changes_what_the_weights_add_up_to` could not see it: every
    // height in that fixture is comfortably above two.
    if layout.rows.get(row).is_some_and(|entry| entry.height == 1) {
        for entry in &mut layout.rows {
            entry.height = entry.height.saturating_mul(2);
        }
    }

    let source = layout.rows.get_mut(row)?;
    let panel = source.panels.remove(column);

    // The new row's height comes out of the row the panel left, so the total is
    // unchanged and every other row keeps the share the user gave it.
    //
    // A source of height 0 gives 0, which is right rather than a special case: a
    // row with no weight draws nothing, and a panel promoted out of one has not
    // asked to start being visible.
    let height = source.height;
    let taken = height / 2;
    source.height = height - taken;

    let at = if below { row + 1 } else { row };
    layout.rows.insert(
        at,
        LayoutRow {
            height: taken,
            panels: vec![panel],
        },
    );
    Some((at, 0))
}

/// Close `emptied` if the departure left it with nothing, returning where
/// `target` ended up once the rows shifted.
fn close_if_empty(layout: &mut Layout, emptied: usize, target: usize) -> usize {
    if !layout.rows[emptied].panels.is_empty() {
        return target;
    }
    // The height goes to the row that took the panel, rather than being shared
    // out: the panel is still on screen, and it keeps roughly the room it had.
    let freed = layout.rows[emptied].height;
    layout.rows[target].height = layout.rows[target].height.saturating_add(freed);
    layout.rows.remove(emptied);
    if emptied < target { target - 1 } else { target }
}

/// Where the middle of this panel sits across its row, as a fraction.
fn centre_of(row: &LayoutRow, column: usize) -> f64 {
    let weight = |panel: &crate::config::LayoutPanel| f64::from(panel.width.max(1));
    let total: f64 = row.panels.iter().map(weight).sum();
    if total <= 0.0 {
        return 0.0;
    }
    let before: f64 = row.panels.iter().take(column).map(weight).sum();
    let own = row.panels.get(column).map_or(1.0, weight);
    (before + own / 2.0) / total
}

/// The gap between panels nearest to `centre`, as an index to insert at.
fn insertion_point(row: &LayoutRow, centre: f64) -> usize {
    let weight = |panel: &crate::config::LayoutPanel| f64::from(panel.width.max(1));
    let total: f64 = row.panels.iter().map(weight).sum();
    if total <= 0.0 {
        return 0;
    }

    let mut best = 0;
    let mut closest = f64::MAX;
    let mut running = 0.0;
    for index in 0..=row.panels.len() {
        let gap = (running / total - centre).abs();
        if gap < closest {
            closest = gap;
            best = index;
        }
        if let Some(panel) = row.panels.get(index) {
            running += weight(panel);
        }
    }
    best
}

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

    fn layout(rows: &[(u16, &[(&str, u16)])]) -> Layout {
        Layout {
            rows: rows
                .iter()
                .map(|(height, panels)| LayoutRow {
                    height: *height,
                    panels: panels
                        .iter()
                        .map(|(widget, width)| LayoutPanel {
                            widget: (*widget).into(),
                            width: *width,
                        })
                        .collect(),
                })
                .collect(),
        }
    }

    fn shape(layout: &Layout) -> Vec<Vec<String>> {
        layout
            .rows
            .iter()
            .map(|row| row.panels.iter().map(|p| p.widget.clone()).collect())
            .collect()
    }

    fn heights(layout: &Layout) -> Vec<u16> {
        layout.rows.iter().map(|row| row.height).collect()
    }

    #[test]
    fn a_panel_swaps_with_its_neighbour_and_keeps_its_width() {
        let mut l = layout(&[(100, &[("clocks", 26), ("calendar", 34), ("weather", 40)])]);
        assert_eq!(move_panel(&mut l, 0, 0, Direction::Right), Some((0, 1)));

        assert_eq!(shape(&l)[0], ["calendar", "clocks", "weather"]);
        // The width travelled. Had the widgets swapped instead of the entries,
        // clocks would be sitting in calendar's 34 and calendar in clocks' 26.
        let clocks = l.rows[0]
            .panels
            .iter()
            .find(|p| p.widget == "clocks")
            .unwrap();
        assert_eq!(clocks.width, 26, "clocks kept the width it was given");
    }

    #[test]
    fn the_ends_of_a_row_refuse_rather_than_wrapping() {
        let mut l = layout(&[(100, &[("clocks", 50), ("weather", 50)])]);
        assert_eq!(move_panel(&mut l, 0, 0, Direction::Left), None);
        assert_eq!(move_panel(&mut l, 0, 1, Direction::Right), None);
        assert_eq!(shape(&l)[0], ["clocks", "weather"], "nothing moved");
    }

    /// The whole reason a move lands by position rather than by index: the
    /// rightmost panel of a narrow row belongs on the right of a wider one.
    #[test]
    fn a_panel_lands_under_where_it_already_was() {
        let mut l = layout(&[
            (50, &[("a", 10), ("b", 10), ("c", 80)]),
            (50, &[("w", 25), ("x", 25), ("y", 25), ("z", 25)]),
        ]);
        // `c` occupies the right 80% of its row, so its middle is at 60%.
        assert_eq!(move_panel(&mut l, 0, 2, Direction::Down), Some((1, 2)));
        assert_eq!(shape(&l)[1], ["w", "x", "c", "y", "z"]);

        // And the leftmost lands leftmost, not at the same index it left.
        let mut l = layout(&[
            (50, &[("a", 10), ("b", 90)]),
            (50, &[("w", 25), ("x", 25), ("y", 25), ("z", 25)]),
        ]);
        assert_eq!(move_panel(&mut l, 0, 0, Direction::Down), Some((1, 0)));
        assert_eq!(shape(&l)[1], ["a", "w", "x", "y", "z"]);
    }

    #[test]
    fn the_last_panel_out_of_a_row_closes_it_and_hands_over_the_height() {
        let mut l = layout(&[(30, &[("clocks", 100)]), (70, &[("todo", 100)])]);
        assert_eq!(move_panel(&mut l, 0, 0, Direction::Down), Some((0, 0)));

        assert_eq!(l.rows.len(), 1, "the emptied row closed");
        assert_eq!(shape(&l)[0], ["clocks", "todo"]);
        assert_eq!(heights(&l), [100], "and its height went to the survivor");
    }

    #[test]
    fn pushing_past_the_edge_opens_a_row_without_inventing_weight() {
        let mut l = layout(&[
            (40, &[("clocks", 50), ("weather", 50)]),
            (60, &[("todo", 100)]),
        ]);
        assert_eq!(move_panel(&mut l, 0, 0, Direction::Up), Some((0, 0)));

        assert_eq!(shape(&l), [vec!["clocks"], vec!["weather"], vec!["todo"]]);
        assert_eq!(heights(&l), [20, 20, 60]);
        assert_eq!(
            heights(&l).iter().sum::<u16>(),
            100,
            "a new row is paid for out of the one it left, not conjured"
        );
    }

    /// Otherwise holding the key at the edge would spawn a row per repeat, each
    /// one a move that changed nothing.
    #[test]
    fn a_panel_that_already_has_its_own_row_will_not_take_another() {
        let mut l = layout(&[(50, &[("clocks", 100)]), (50, &[("todo", 100)])]);
        assert_eq!(move_panel(&mut l, 0, 0, Direction::Up), None);
        assert_eq!(l.rows.len(), 2, "no row was opened");
        assert_eq!(heights(&l), [50, 50], "and no weight was moved");
    }

    /// The rule at the top of this module, stated as the property it is really
    /// about: an untouched row keeps its *share* of the dashboard.
    ///
    /// The sum-based test below cannot see the case this exists for. Every
    /// height in its fixture is comfortably above two, and the bug only showed
    /// up at one: `source.height.max(2)` turned a row of height 1 into two rows
    /// of 1, so `[1, 1]` became `[1, 1, 1]` and a row nobody had moved went from
    /// half the screen to a third of it.
    #[test]
    fn promoting_out_of_a_thin_row_does_not_rescale_the_rows_around_it() {
        for height in [0u16, 1, 2, 3, 7, 100] {
            let mut l = layout(&[
                (height, &[("clocks", 50), ("weather", 50)]),
                (50, &[("todo", 100)]),
            ]);
            let before: u16 = heights(&l).iter().sum();
            let untouched_share = f64::from(50) / f64::from(before.max(1));

            assert_eq!(
                move_panel(&mut l, 0, 0, Direction::Up),
                Some((0, 0)),
                "height {height}: the move itself must still work"
            );

            let after: u16 = heights(&l).iter().sum();
            let todo = *heights(&l).last().expect("the untouched row");
            let share = f64::from(todo) / f64::from(after.max(1));
            assert!(
                (share - untouched_share).abs() < 1e-9,
                "height {height}: the untouched row went from {:.4} of the screen \
                 to {:.4} — heights {:?}",
                untouched_share,
                share,
                heights(&l)
            );
        }
    }

    /// `validate` refuses a layout with no rows, and a row with no panels. A
    /// gesture the user can hold down must not be able to produce either.
    #[test]
    fn no_sequence_of_moves_can_produce_a_layout_the_config_would_reject() {
        let start = layout(&[
            (1, &[("clocks", 26), ("calendar", 74)]),
            (1, &[("todo", 100)]),
            (2, &[("cpu", 50), ("network", 50)]),
        ]);

        // Every direction, from every position, repeatedly — which is what
        // holding the key down amounts to.
        let mut l = start;
        for step in 0..200usize {
            let direction = match step % 4 {
                0 => Direction::Down,
                1 => Direction::Right,
                2 => Direction::Up,
                _ => Direction::Left,
            };
            let row = step % l.rows.len().max(1);
            let column = step % l.rows[row].panels.len().max(1);
            move_panel(&mut l, row, column, direction);

            assert!(!l.rows.is_empty(), "step {step}: the layout emptied");
            for entry in &l.rows {
                assert!(
                    !entry.panels.is_empty(),
                    "step {step}: an empty row survived: {:?}",
                    shape(&l)
                );
            }
            let mut placed: Vec<&str> = l.widgets();
            placed.sort_unstable();
            assert_eq!(
                placed,
                ["calendar", "clocks", "cpu", "network", "todo"],
                "step {step}: a panel was lost or duplicated"
            );
        }
    }

    /// The one panel on the dashboard has nowhere to go in any direction, and
    /// must not be able to leave the layout empty by trying.
    #[test]
    fn the_only_panel_on_the_dashboard_refuses_every_direction() {
        for direction in [
            Direction::Left,
            Direction::Right,
            Direction::Up,
            Direction::Down,
        ] {
            let mut l = layout(&[(100, &[("clocks", 100)])]);
            assert_eq!(move_panel(&mut l, 0, 0, direction), None, "{direction:?}");
            assert_eq!(shape(&l), [["clocks"]], "{direction:?} moved something");
        }
    }

    #[test]
    fn a_move_never_changes_what_the_weights_add_up_to() {
        let mut l = layout(&[
            (34, &[("clocks", 26), ("calendar", 34), ("weather", 40)]),
            (42, &[("todo", 40), ("agenda", 32), ("notes", 28)]),
            (24, &[("cpu", 50), ("network", 50)]),
        ]);
        let before: u16 = heights(&l).iter().sum();

        for direction in [
            Direction::Down,
            Direction::Down,
            Direction::Up,
            Direction::Right,
            Direction::Up,
        ] {
            move_panel(&mut l, 0, 0, direction);
            assert_eq!(
                heights(&l).iter().sum::<u16>(),
                before,
                "after {direction:?}: {:?}",
                heights(&l)
            );
        }
    }
}