oxker 0.13.2

A simple tui to view & control docker containers
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
use std::fmt::Display;

use ratatui::{
    Frame,
    layout::{Alignment, Direction, Layout, Rect},
    style::{Color, Modifier, Style, Stylize},
    symbols,
    text::Span,
    widgets::{Axis, Block, BorderType, Borders, Chart, Dataset, GraphType},
};

use super::{CONSTRAINT_50_50, FrameData};
use crate::{
    app_data::{State, Stats},
    config::AppColors,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChartVariant {
    Cpu,
    Memory,
}

impl ChartVariant {
    const fn name(self) -> &'static str {
        match self {
            Self::Cpu => "cpu",
            Self::Memory => "memory",
        }
    }

    const fn get_title_color(self, colors: AppColors, state: State) -> Color {
        if state.is_healthy() {
            match self {
                Self::Cpu => colors.chart_cpu.title,
                Self::Memory => colors.chart_memory.title,
            }
        } else {
            state.get_color(colors)
        }
    }

    const fn get_bg_color(self, colors: AppColors) -> Color {
        match self {
            Self::Cpu => colors.chart_cpu.background,
            Self::Memory => colors.chart_memory.background,
        }
    }

    const fn get_border_color(self, colors: AppColors) -> Color {
        match self {
            Self::Cpu => colors.chart_cpu.border,
            Self::Memory => colors.chart_memory.border,
        }
    }

    const fn get_y_axis_color(self, colors: AppColors) -> Color {
        match self {
            Self::Cpu => colors.chart_cpu.y_axis,
            Self::Memory => colors.chart_memory.y_axis,
        }
    }

    const fn get_max_color(self, colors: AppColors, state: State) -> Color {
        if state.is_healthy() {
            match self {
                Self::Cpu => colors.chart_cpu.max,
                Self::Memory => colors.chart_memory.max,
            }
        } else {
            state.get_color(colors)
        }
    }
}

/// Create charts
fn make_chart<'a, T: Stats + Display>(
    chart_variant: ChartVariant,
    colors: AppColors,
    current: &'a T,
    dataset: Vec<Dataset<'a>>,
    max: &'a T,
    state: State,
) -> Chart<'a> {
    let max_color = chart_variant.get_max_color(colors, state);

    Chart::new(dataset)
        .bg(chart_variant.get_bg_color(colors))
        .block(
            Block::default()
                .style(Style::default().bg(chart_variant.get_bg_color(colors)))
                .title_alignment(Alignment::Center)
                .title(Span::styled(
                    format!(" {} {current} ", chart_variant.name()),
                    Style::default()
                        .fg(chart_variant.get_title_color(colors, state))
                        .add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(chart_variant.get_border_color(colors))),
        )
        .x_axis(Axis::default().bounds([0.00, 60.0]))
        .y_axis(
            Axis::default()
                .labels(vec![
                    Span::styled("", Style::default().fg(max_color)),
                    Span::styled(
                        format!("{max}"),
                        Style::default().add_modifier(Modifier::BOLD).fg(max_color),
                    ),
                ])
                .style(Style::new().fg(chart_variant.get_y_axis_color(colors)))
                // Add 0.01, so that max point is always visible?
                .bounds([0.0, max.get_value() + 0.01]),
        )
}

/// Draw the cpu + mem charts
pub fn draw(area: Rect, colors: AppColors, f: &mut Frame, fd: &FrameData) {
    if let Some(x) = fd.chart_data.as_ref() {
        let area = Layout::default()
            .direction(Direction::Horizontal)
            .constraints(CONSTRAINT_50_50)
            .split(area);

        let cpu_dataset = vec![
            Dataset::default()
                .marker(symbols::Marker::Dot)
                .style(Style::default().fg(colors.chart_cpu.points))
                .graph_type(GraphType::Line)
                .data(&x.cpu.dataset),
        ];
        let mem_dataset = vec![
            Dataset::default()
                .marker(symbols::Marker::Dot)
                .style(Style::default().fg(colors.chart_memory.points))
                .graph_type(GraphType::Line)
                .data(&x.memory.dataset),
        ];

        // let cpu_stats = CpuStats::new(cpu.0.last().map_or(0.00, |f| f.1));
        // #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        // let mem_stats = ByteStats::new(mem.0.last().map_or(0, |f| f.1 as u64));
        let cpu_chart = make_chart(
            ChartVariant::Cpu,
            colors,
            &x.cpu.current,
            cpu_dataset,
            &x.cpu.max,
            x.state,
        );
        let mem_chart = make_chart(
            ChartVariant::Memory,
            colors,
            &x.memory.current,
            mem_dataset,
            &x.memory.max,
            x.state,
        );

        f.render_widget(cpu_chart, area[0]);
        f.render_widget(mem_chart, area[1]);
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use insta::assert_snapshot;
    use ratatui::style::{Color, Modifier};

    use crate::{
        app_data::State,
        config::AppColors,
        ui::{
            FrameData,
            draw_blocks::tests::{COLOR_ORANGE, get_result, insert_all_chart_data, test_setup},
        },
    };

    /// CPU and Memory charts used in multiple tests, based on data from above insert_chart_data()
    const _EXPECTED: [&str; 10] = [
        "╭───────────── cpu 03.00% ─────────────╮╭────────── memory 30.00 kB ───────────╮",
        "│10.00%│    •                          ││100.00 kB│   ••                       │",
        "│      │   ••                          ││         │   ••                       │",
        "│      │  •••                          ││         │  • •                       │",
        "│      │  • •                          ││         │ •  •                       │",
        "│      │ •   ••                        ││         │••  ••                      │",
        "│      │•    •                         ││         │•   •                       │",
        "│      │•    •                         ││         │•   •                       │",
        "│      │                               ││         │                            │",
        "╰──────────────────────────────────────╯╰──────────────────────────────────────╯",
    ];

    // co-ordinates of the dots from the cpu chart
    const CPU_XY: [(usize, usize); 16] = [
        (1, 13),
        (2, 12),
        (2, 13),
        (3, 11),
        (3, 13),
        (4, 11),
        (4, 13),
        (5, 10),
        (5, 13),
        (6, 9),
        (6, 13),
        (6, 14),
        (7, 8),
        (7, 9),
        (7, 13),
        (7, 14),
    ];

    // co-ordinates of the dots from the memory chart
    const MEM_XY: [(usize, usize); 14] = [
        (1, 55),
        (2, 54),
        (2, 55),
        (3, 54),
        (3, 55),
        (4, 53),
        (4, 55),
        (5, 52),
        (5, 53),
        (5, 56),
        (6, 52),
        (6, 56),
        (7, 51),
        (7, 56),
    ];

    #[test]
    /// When status is Running, but not data, charts drawn without dots etc, colours correct
    fn test_draw_blocks_charts_running_none() {
        let mut setup = test_setup(80, 10, true, true);

        let fd = FrameData::from((&setup.app_data, &setup.gui_state));
        setup
            .terminal
            .draw(|f| {
                super::draw(setup.area, setup.app_data.lock().config.app_colors, f, &fd);
            })
            .unwrap();
        assert_snapshot!(setup.terminal.backend());

        for (row_index, result_row) in get_result(&setup) {
            for (result_cell_index, result_cell) in result_row.iter().enumerate() {
                match (row_index, result_cell_index) {
                    (0, 14..=25 | 52..=67) => {
                        assert_eq!(result_cell.fg, Color::Green);
                        assert_eq!(result_cell.modifier, Modifier::BOLD);
                    }
                    (1, 1..=6 | 41..=47) => {
                        assert_eq!(result_cell.fg, COLOR_ORANGE);
                        assert_eq!(result_cell.modifier, Modifier::BOLD);
                    }
                    (2..=8, 1..=6 | 8..=38 | 49..=78 | 41..=47) | (1, 8..=38 | 49..=78) => {
                        assert_eq!(result_cell.fg, Color::Reset);
                        assert!(result_cell.modifier.is_empty());
                    }
                    _ => {
                        assert_eq!(result_cell.fg, Color::White);
                        assert!(result_cell.modifier.is_empty());
                    }
                }
            }
        }
    }

    #[test]
    /// When status is Running, charts correctly drawn
    fn test_draw_blocks_charts_running_some() {
        let mut setup = test_setup(80, 10, true, true);

        insert_all_chart_data(&setup);
        let fd = FrameData::from((&setup.app_data, &setup.gui_state));

        setup
            .terminal
            .draw(|f| {
                super::draw(setup.area, setup.app_data.lock().config.app_colors, f, &fd);
            })
            .unwrap();

        assert_snapshot!(setup.terminal.backend());

        for (row_index, result_row) in get_result(&setup) {
            for (result_cell_index, result_cell) in result_row.iter().enumerate() {
                match (row_index, result_cell_index) {
                    (0, 14..=25 | 51..=67) => {
                        assert_eq!(result_cell.fg, Color::Green);
                        assert_eq!(result_cell.modifier, Modifier::BOLD);
                    }
                    (1, 1..=6 | 41..=49) => {
                        assert_eq!(result_cell.fg, COLOR_ORANGE);
                        assert_eq!(result_cell.modifier, Modifier::BOLD);
                    }
                    xy if CPU_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Magenta);
                        assert!(result_cell.modifier.is_empty());
                    }
                    xy if MEM_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Cyan);
                        assert!(result_cell.modifier.is_empty());
                    }
                    (0 | 9, 0..=80) | (1..=9, 0 | 7 | 39 | 40 | 50 | 79) => {
                        assert_eq!(result_cell.fg, Color::White);
                        assert!(result_cell.modifier.is_empty());
                    }
                    _ => {
                        assert_eq!(result_cell.fg, Color::Reset);
                        assert!(result_cell.modifier.is_empty());
                    }
                }
            }
        }
    }

    #[test]
    /// Whens status paused, some text is now Yellow
    fn test_draw_blocks_charts_paused() {
        let mut setup = test_setup(80, 10, true, true);

        insert_all_chart_data(&setup);
        setup.app_data.lock().containers.items[0].state = State::Paused;
        let fd = FrameData::from((&setup.app_data, &setup.gui_state));

        setup
            .terminal
            .draw(|f| {
                super::draw(setup.area, setup.app_data.lock().config.app_colors, f, &fd);
            })
            .unwrap();

        assert_snapshot!(setup.terminal.backend());
        //

        for (row_index, result_row) in get_result(&setup) {
            for (result_cell_index, result_cell) in result_row.iter().enumerate() {
                match (row_index, result_cell_index) {
                    (0, 14..=25 | 51..=67) | (1, 1..=6 | 41..=49) => {
                        assert_eq!(result_cell.fg, Color::Yellow);
                        assert_eq!(result_cell.modifier, Modifier::BOLD);
                    }
                    xy if CPU_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Magenta);
                        assert!(result_cell.modifier.is_empty());
                    }
                    xy if MEM_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Cyan);
                        assert!(result_cell.modifier.is_empty());
                    }
                    (0 | 9, 0..=80) | (1..=9, 0 | 7 | 39 | 40 | 50 | 79) => {
                        assert_eq!(result_cell.fg, Color::White);
                        assert!(result_cell.modifier.is_empty());
                    }
                    _ => {
                        assert_eq!(result_cell.fg, Color::Reset);
                        assert!(result_cell.modifier.is_empty());
                    }
                }
            }
        }
    }

    #[test]
    /// When dead, text is red
    fn test_draw_blocks_charts_dead() {
        let mut setup = test_setup(80, 10, true, true);
        insert_all_chart_data(&setup);
        setup.app_data.lock().containers.items[0].state = State::Dead;
        let fd = FrameData::from((&setup.app_data, &setup.gui_state));

        setup
            .terminal
            .draw(|f| {
                super::draw(setup.area, setup.app_data.lock().config.app_colors, f, &fd);
            })
            .unwrap();
        assert_snapshot!(setup.terminal.backend());
        for (row_index, result_row) in get_result(&setup) {
            for (result_cell_index, result_cell) in result_row.iter().enumerate() {
                match (row_index, result_cell_index) {
                    (0, 14..=25 | 51..=67) | (1, 1..=6 | 41..=49) => {
                        assert_eq!(result_cell.fg, Color::Red);
                        assert_eq!(result_cell.modifier, Modifier::BOLD);
                    }
                    xy if CPU_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Magenta);
                        assert!(result_cell.modifier.is_empty());
                    }
                    xy if MEM_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Cyan);
                        assert!(result_cell.modifier.is_empty());
                    }
                    (0 | 9, 0..=80) | (1..=9, 0 | 7 | 39 | 40 | 50 | 79) => {
                        assert_eq!(result_cell.fg, Color::White);
                        assert!(result_cell.modifier.is_empty());
                    }
                    _ => {
                        assert_eq!(result_cell.fg, Color::Reset);
                        assert!(result_cell.modifier.is_empty());
                    }
                }
            }
        }
    }

    #[test]
    /// Custom colos correctly applied to each part of the charts
    fn test_draw_blocks_charts_custom_colors() {
        let mut colors = AppColors::new();

        colors.chart_cpu.background = Color::White;
        colors.chart_cpu.border = Color::Red;
        colors.chart_cpu.title = Color::Green;
        colors.chart_cpu.max = Color::Magenta;
        colors.chart_cpu.points = Color::Black;
        colors.chart_cpu.y_axis = Color::Blue;

        colors.chart_memory.background = Color::White;
        colors.chart_memory.border = Color::Red;
        colors.chart_memory.title = Color::Green;
        colors.chart_memory.max = Color::Magenta;
        colors.chart_memory.points = Color::Black;
        colors.chart_memory.y_axis = Color::Blue;

        let mut setup = test_setup(80, 10, true, true);

        insert_all_chart_data(&setup);
        let fd = FrameData::from((&setup.app_data, &setup.gui_state));

        setup
            .terminal
            .draw(|f| {
                super::draw(setup.area, colors, f, &fd);
            })
            .unwrap();

        assert_snapshot!(setup.terminal.backend());

        for (row_index, result_row) in get_result(&setup) {
            for (result_cell_index, result_cell) in result_row.iter().enumerate() {
                assert_eq!(result_cell.bg, Color::White);

                match (row_index, result_cell_index) {
                    // border
                    (0, 0..=13 | 26..=50 | 68..=79) | (9, _) | (1..=8, 0 | 39 | 40 | 79) => {
                        assert_eq!(result_cell.fg, Color::Red);
                    }
                    // title
                    (0, 14..=25 | 51..=67) => {
                        assert_eq!(result_cell.fg, Color::Green);
                    }
                    // max label
                    (1, 1..=6 | 41..=49) => {
                        assert_eq!(result_cell.fg, Color::Magenta);
                    }
                    // data points
                    xy if CPU_XY.contains(&xy) | MEM_XY.contains(&xy) => {
                        assert_eq!(result_cell.fg, Color::Black);
                    }
                    // y axis
                    (1..=8, 7 | 50) => {
                        assert_eq!(result_cell.fg, Color::Blue);
                    }
                    _ => {
                        assert_eq!(result_cell.fg, Color::Reset);
                    }
                }
            }
        }
    }
}