summaryrefslogtreecommitdiffstats
path: root/src/canvas/widgets/temp_table.rs
blob: f4e6a9c1cbcf50dfae4361812df05d850be68ee9 (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
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
use once_cell::sync::Lazy;
use tui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout, Rect},
    terminal::Frame,
    text::Span,
    text::Spans,
    widgets::{Block, Borders, Row, Table},
};

use crate::{
    app,
    canvas::{
        drawing_utils::{get_column_widths, get_start_position},
        Painter,
    },
    constants::*,
};
use std::borrow::Cow;
use unicode_segmentation::UnicodeSegmentation;

const TEMP_HEADERS: [&str; 2] = ["Sensor", "Temp"];

static TEMP_HEADERS_LENS: Lazy<Vec<u16>> = Lazy::new(|| {
    TEMP_HEADERS
        .iter()
        .map(|entry| entry.len() as u16)
        .collect::<Vec<_>>()
});

pub trait TempTableWidget {
    fn draw_temp_table<B: Backend>(
        &self, f: &mut Frame<'_, B>, app_state: &mut app::App, draw_loc: Rect, draw_border: bool,
        widget_id: u64,
    );
}

impl TempTableWidget for Painter {
    fn draw_temp_table<B: Backend>(
        &self, f: &mut Frame<'_, B>, app_state: &mut app::App, draw_loc: Rect, draw_border: bool,
        widget_id: u64,
    ) {
        let recalculate_column_widths = app_state.should_get_widget_bounds();
        if let Some(temp_widget_state) = app_state.temp_state.widget_states.get_mut(&widget_id) {
            let table_gap = if draw_loc.height < TABLE_GAP_HEIGHT_LIMIT {
                0
            } else {
                app_state.app_config_fields.table_gap
            };
            let start_position = get_start_position(
                usize::from(
                    (draw_loc.height + (1 - table_gap)).saturating_sub(self.table_height_offset),
                ),
                &temp_widget_state.scroll_state.scroll_direction,
                &mut temp_widget_state.scroll_state.previous_scroll_position,
                temp_widget_state.scroll_state.current_scroll_position,
                app_state.is_force_redraw,
            );
            let is_on_widget = widget_id == app_state.current_widget.widget_id;
            let temp_table_state = &mut temp_widget_state.scroll_state.table_state;
            temp_table_state.select(Some(
                temp_widget_state
                    .scroll_state
                    .current_scroll_position
                    .saturating_sub(start_position),
            ));
            let sliced_vec = &app_state.canvas_data.temp_sensor_data[start_position..];

            // Calculate widths
            let hard_widths = [None, None];
            if recalculate_column_widths {
                temp_widget_state.table_width_state.desired_column_widths = {
                    let mut column_widths = TEMP_HEADERS_LENS.clone();
                    for row in sliced_vec {
                        for (col, entry) in row.iter().enumerate() {
                            if entry.len() as u16 > column_widths[col] {
                                column_widths[col] = entry.len() as u16;
                            }
                        }
                    }

                    column_widths
                };
                temp_widget_state.table_width_state.calculated_column_widths = get_column_widths(
                    draw_loc.width,
                    &hard_widths,
                    &(TEMP_HEADERS_LENS
                        .iter()
                        .map(|width| Some(*width))
                        .collect::<Vec<_>>()),
                    &[Some(0.80), Some(-1.0)],
                    &temp_widget_state
                        .table_width_state
                        .desired_column_widths
                        .iter()
                        .map(|width| Some(*width))
                        .collect::<Vec<_>>(),
                    false,
                );
            }

            let dcw = &temp_widget_state.table_width_state.desired_column_widths;
            let ccw = &temp_widget_state.table_width_state.calculated_column_widths;
            let temperature_rows =
                sliced_vec.iter().map(|temp_row| {
                    let truncated_data = temp_row.iter().zip(&hard_widths).enumerate().map(
                        |(itx, (entry, width))| {
                            if width.is_none() {
                                if let (Some(desired_col_width), Some(calculated_col_width)) =
                                    (dcw.get(itx), ccw.get(itx))
                                {
                                    if *desired_col_width > *calculated_col_width
                                        && *calculated_col_width > 0
                                    {
                                        let graphemes =
                                            UnicodeSegmentation::graphemes(entry.as_str(), true)
                                                .collect::<Vec<&str>>();

                                        if graphemes.len() > *calculated_col_width as usize
                                            && *calculated_col_width > 1
                                        {
                                            // Truncate with ellipsis
                                            let first_n = graphemes
                                                [..(*calculated_col_width as usize - 1)]
                                                .concat();
                                            Cow::Owned(format!("{}…", first_n))
                                        } else {
                                            Cow::Borrowed(entry)
                                        }
                                    } else {
                                        Cow::Borrowed(entry)
                                    }
                                } else {
                                    Cow::Borrowed(entry)
                                }
                            } else {
                                Cow::Borrowed(entry)
                            }
                        },
                    );

                    Row::Data(truncated_data)
                });

            let (border_style, highlight_style) = if is_on_widget {
                (
                    self.colours.highlighted_border_style,
                    self.colours.currently_selected_text_style,
                )
            } else {
                (self.colours.border_style, self.colours.text_style)
            };

            let title_base = if app_state.app_config_fields.show_table_scroll_position {
                let title_string = format!(
                    " Temperatures ({} of {}) ",
                    temp_widget_state
                        .scroll_state
                        .current_scroll_position
                        .saturating_add(1),
                    app_state.canvas_data.temp_sensor_data.len()
                );

                if title_string.len() <= draw_loc.width as usize {
                    title_string
                } else {
                    " Temperatures ".to_string()
                }
            } else {
                " Temperatures ".to_string()
            };

            let title = if app_state.is_expanded {
                const ESCAPE_ENDING: &str = "── Esc to go back ";

                let (chosen_title_base, expanded_title_base) = {
                    let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING);

                    if temp_title_base.len() > draw_loc.width as usize {
                        (
                            " Temperatures ".to_string(),
                            format!("{}{}", " Temperatures ".to_string(), ESCAPE_ENDING),
                        )
                    } else {
                        (title_base, temp_title_base)
                    }
                };

                Spans::from(vec![
                    Span::styled(chosen_title_base, self.colours.widget_title_style),
                    Span::styled(
                        format!(
                            "─{}─ Esc to go back ",
                            "─".repeat(
                                usize::from(draw_loc.width).saturating_sub(
                                    UnicodeSegmentation::graphemes(
                                        expanded_title_base.as_str(),
                                        true
                                    )
                                    .count()
                                        + 2
                                )
                            )
                        ),
                        border_style,
                    ),
                ])
            } else {
                Spans::from(Span::styled(title_base, self.colours.widget_title_style))
            };

            let temp_block = if draw_border {
                Block::default()
                    .title(title)
                    .borders(Borders::ALL)
                    .border_style(border_style)
            } else if is_on_widget {
                Block::default()
                    .borders(*SIDE_BORDERS)
                    .border_style(self.colours.highlighted_border_style)
            } else {
                Block::default().borders(Borders::NONE)
            };

            let margined_draw_loc = Layout::default()
                .constraints([Constraint::Percentage(100)])
                .horizontal_margin(if is_on_widget || draw_border { 0 } else { 1 })
                .direction(Direction::Horizontal)
                .split(draw_loc)[0];

            // Draw
            f.render_stateful_widget(
                Table::new(TEMP_HEADERS.iter(), temperature_rows)
                    .block(temp_block)
                    .header_style(self.colours.table_header_style)
                    .highlight_style(highlight_style)
                    .style(self.colours.text_style)
                    .widths(
                        &(te