summaryrefslogtreecommitdiffstats
path: root/src/app/widgets/bottom_widgets/basic_cpu.rs
blob: f4aa443536dfa29d0f3b43ee6b7cfc5386503b2c (plain)
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
use std::cmp::max;

use tui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout, Rect},
    widgets::Block,
    Frame,
};

use crate::{
    app::{widgets::tui_stuff::PipeGauge, AppConfigFields, Component, DataCollection, Widget},
    canvas::Painter,
    constants::SIDE_BORDERS,
    options::layout_options::LayoutRule,
};

const REQUIRED_COLUMNS: usize = 4;

#[derive(Debug)]
pub struct BasicCpu {
    bounds: Rect,
    display_data: Vec<(f64, String, String)>,
    width: LayoutRule,
    showing_avg: bool,
}

impl BasicCpu {
    /// Creates a new [`BasicCpu`] given a [`AppConfigFields`].
    pub fn from_config(app_config_fields: &AppConfigFields) -> Self {
        Self {
            bounds: Default::default(),
            display_data: Default::default(),
            width: Default::default(),
            showing_avg: app_config_fields.show_average_cpu,
        }
    }

    /// Sets the width.
    pub fn width(mut self, width: LayoutRule) -> Self {
        self.width = width;
        self
    }
}

impl Component for BasicCpu {
    fn bounds(&self) -> Rect {
        self.bounds
    }

    fn set_bounds(&mut self, new_bounds: Rect) {
        self.bounds = new_bounds;
    }
}

impl Widget for BasicCpu {
    fn get_pretty_name(&self) -> &'static str {
        "CPU"
    }

    fn draw<B: Backend>(
        &mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect, selected: bool,
        _expanded: bool,
    ) {
        const CONSTRAINTS: [Constraint; 2 * REQUIRED_COLUMNS - 1] = [
            Constraint::Ratio(1, REQUIRED_COLUMNS as u32),
            Constraint::Length(2),
            Constraint::Ratio(1, REQUIRED_COLUMNS as u32),
            Constraint::Length(2),
            Constraint::Ratio(1, REQUIRED_COLUMNS as u32),
            Constraint::Length(2),
            Constraint::Ratio(1, REQUIRED_COLUMNS as u32),
        ];
        let block = Block::default()
            .borders(*SIDE_BORDERS)
            .border_style(painter.colours.highlighted_border_style);
        let inner_area = block.inner(area);
        let split_area = Layout::default()
            .direction(Direction::Horizontal)
            .constraints(CONSTRAINTS)
            .split(inner_area)
            .into_iter()
            .enumerate()
            .filter_map(
                |(index, rect)| {
                    if index % 2 == 0 {
                        Some(rect)
                    } else {
                        None
                    }
                },
            );

        let display_data_len = self.display_data.len();
        let length = display_data_len / REQUIRED_COLUMNS;
        let largest_height = max(
            1,
            length
                + (if display_data_len % REQUIRED_COLUMNS == 0 {
                    0
                } else {
                    1
                }),
        );
        let mut leftover = display_data_len % REQUIRED_COLUMNS;
        let column_heights = (0..REQUIRED_COLUMNS).map(|_| {
            if leftover > 0 {
                leftover -= 1;
                length + 1
            } else {
                length
            }
        });

        if selected {
            f.render_widget(block, area);
        }

        let mut index_offset = 0;
        split_area
            .into_iter()
            .zip(column_heights)
            .for_each(|(area, height)| {
                let column_areas = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints(vec![Constraint::Length(1); largest_height])
                    .split(area);

                let num_entries = if index_offset + height < display_data_len {
                    height
                } else {
                    display_data_len - index_offset
                };
                let end = index_offset + num_entries;

                self.display_data[index_offset..end]
                    .iter()
                    .zip(column_areas)
                    .enumerate()
                    .for_each(|(column_index, ((percent, label, usage_label), area))| {
                        let cpu_index = index_offset + column_index;
                        let style = if cpu_index == 0 {
                            painter.colours.avg_colour_style
                        } else {
                            let cpu_style_index = if self.showing_avg {
                                cpu_index - 1
                            } else {
                                cpu_index
                            };
                            painter.colours.cpu_colour_styles
                                [cpu_style_index % painter.colours.cpu_colour_styles.len()]
                        };

                        f.render_widget(
                            PipeGauge::default()
                                .ratio(*percent)
                                .style(style)
                                .gauge_style(style)
                                .start_label(label.clone())
                                .end_label(usage_label.clone()),
                            area,
                        );
                    });

                index_offset = end;
            });
    }

    fn update_data(&mut self, data_collection: &DataCollection) {
        self.display_data = data_collection
            .cpu_harvest
            .iter()
            .map(|data| {
                (
                    data.cpu_usage / 100.0,
                    format!(
                        "{:3}",
                        data.cpu_count
                            .map(|c| c.to_string())
                            .unwrap_or_else(|| data.cpu_prefix.clone())
                    ),
                    format!("{:3.0}%", data.cpu_usage.round()),
                )
            })
            .collect::<Vec<_>>();
    }

    fn width(&self) -> LayoutRule {
        self.width
    }

    fn height(&self) -> LayoutRule {
        let display_data_len = self.display_data.len();
        let length = max(
            1,
            (display_data_len / REQUIRED_COLUMNS) as u16
                + (if display_data_len % REQUIRED_COLUMNS == 0 {
                    0
                } else {
                    1
                }),
        );

        LayoutRule::Length { length }
    }
}