summaryrefslogtreecommitdiffstats
path: root/src/display/components/table.rs
blob: f61886c659ce92f4deb0a4b5dd9c5b749c6dfac7 (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
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
use ::std::collections::{BTreeMap, HashMap};
use ::std::iter::FromIterator;
use ::unicode_width::UnicodeWidthChar;

use ::tui::backend::Backend;
use ::tui::layout::Rect;
use ::tui::style::{Color, Style};
use ::tui::terminal::Frame;
use ::tui::widgets::{Block, Borders, Row, Widget};

use crate::display::{Bandwidth, DisplayBandwidth, UIState};
use crate::network::{display_connection_string, display_ip_or_host};

use ::std::net::IpAddr;

fn display_upload_and_download(bandwidth: &impl Bandwidth, total: bool) -> String {
    format!(
        "{} / {}",
        DisplayBandwidth {
            bandwidth: bandwidth.get_total_bytes_uploaded() as f64,
            as_rate: !total,
        },
        DisplayBandwidth {
            bandwidth: bandwidth.get_total_bytes_downloaded() as f64,
            as_rate: !total,
        },
    )
}

pub enum ColumnCount {
    Two,
    Three,
}

impl ColumnCount {
    pub fn as_u16(&self) -> u16 {
        match &self {
            ColumnCount::Two => 2,
            ColumnCount::Three => 3,
        }
    }
}

pub struct ColumnData {
    column_count: ColumnCount,
    column_widths: Vec<u16>,
}

pub struct Table<'a> {
    title: &'a str,
    column_names: &'a [&'a str],
    rows: Vec<Vec<String>>,
    breakpoints: BTreeMap<u16, ColumnData>,
}

fn truncate_iter_to_unicode_width<Input, Collect>(iter: Input, width: usize) -> Collect
where
    Input: Iterator<Item = char>,
    Collect: FromIterator<char>,
{
    let mut chunk_width = 0;
    iter.take_while(|ch| {
        chunk_width += ch.width().unwrap_or(0);
        chunk_width <= width
    })
    .collect()
}

fn truncate_middle(row: &str, max_length: u16) -> String {
    if max_length < 6 {
        truncate_iter_to_unicode_width(row.chars(), max_length as usize)
    } else if row.len() as u16 > max_length {
        let split_point = (max_length as usize / 2) - 2;
        let first_slice = truncate_iter_to_unicode_width::<_, String>(row.chars(), split_point);
        let second_slice =
            truncate_iter_to_unicode_width::<_, Vec<_>>(row.chars().rev(), split_point)
                .into_iter()
                .rev()
                .collect::<String>();
        if max_length % 2 == 0 {
            format!("{}[..]{}", first_slice, second_slice)
        } else {
            format!("{}[..]{}", first_slice, second_slice)
        }
    } else {
        row.to_string()
    }
}

impl<'a> Table<'a> {
    pub fn create_connections_table(state: &UIState, ip_to_host: &HashMap<IpAddr, String>) -> Self {
        let connections_rows = state
            .connections
            .iter()
            .map(|(connection, connection_data)| {
                vec![
                    display_connection_string(
                        &connection,
                        &ip_to_host,
                        &connection_data.interface_name,
                    ),
                    connection_data.process_name.to_string(),
                    display_upload_and_download(connection_data, state.cumulative_mode),
                ]
            })
            .collect();
        let connections_title = "Utilization by connection";
        let connections_column_names = &["Connection", "Process", "Up / Down"];
        let mut breakpoints = BTreeMap::new();
        breakpoints.insert(
            0,
            ColumnData {
                column_count: ColumnCount::Two,
                column_widths: vec![20, 23],
            },
        );
        breakpoints.insert(
            70,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![30, 12, 23],
            },
        );
        breakpoints.insert(
            100,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![60, 12, 23],
            },
        );
        breakpoints.insert(
            140,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![100, 12, 23],
            },
        );
        Table {
            title: connections_title,
            column_names: connections_column_names,
            rows: connections_rows,
            breakpoints,
        }
    }
    pub fn create_processes_table(state: &UIState) -> Self {
        let processes_rows = state
            .processes
            .iter()
            .map(|(process_name, data_for_process)| {
                vec![
                    (*process_name).to_string(),
                    data_for_process.connection_count.to_string(),
                    display_upload_and_download(data_for_process, state.cumulative_mode),
                ]
            })
            .collect();
        let processes_title = "Utilization by process name";
        let processes_column_names = &["Process", "Connections", "Up / Down"];
        let mut breakpoints = BTreeMap::new();
        breakpoints.insert(
            0,
            ColumnData {
                column_count: ColumnCount::Two,
                column_widths: vec![12, 23],
            },
        );
        breakpoints.insert(
            50,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![12, 12, 23],
            },
        );
        breakpoints.insert(
            100,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![40, 12, 23],
            },
        );
        breakpoints.insert(
            140,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![40, 12, 23],
            },
        );
        Table {
            title: processes_title,
            column_names: processes_column_names,
            rows: processes_rows,
            breakpoints,
        }
    }
    pub fn create_remote_addresses_table(
        state: &UIState,
        ip_to_host: &HashMap<IpAddr, String>,
    ) -> Self {
        let remote_addresses_rows = state
            .remote_addresses
            .iter()
            .map(|(remote_address, data_for_remote_address)| {
                let remote_address = display_ip_or_host(*remote_address, &ip_to_host);
                vec![
                    remote_address,
                    data_for_remote_address.connection_count.to_string(),
                    display_upload_and_download(data_for_remote_address, state.cumulative_mode),
                ]
            })
            .collect();
        let remote_addresses_title = "Utilization by remote address";
        let remote_addresses_column_names = &["Remote Address", "Connections", "Up / Down"];
        let mut breakpoints = BTreeMap::new();
        breakpoints.insert(
            0,
            ColumnData {
                column_count: ColumnCount::Two,
                column_widths: vec![12, 23],
            },
        );
        breakpoints.insert(
            70,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![30, 12, 23],
            },
        );
        breakpoints.insert(
            100,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![60, 12, 23],
            },
        );
        breakpoints.insert(
            140,
            ColumnData {
                column_count: ColumnCount::Three,
                column_widths: vec![100, 12, 23],
            },
        );
        Table {
            title: remote_addresses_title,
            column_names: remote_addresses_column_names,
            rows: remote_addresses_rows,
            breakpoints,
        }
    }
    pub fn render(&self, frame: &mut Frame<impl Backend>, rect: Rect) {
        let mut column_spacing: u16 = 0;
        let mut widths = &vec![];
        let mut column_count: &ColumnCount = &ColumnCount::Three;

        for (width_breakpoint, column_data) in self.breakpoints.iter() {
            if *width_breakpoint < rect.width {
                widths = &column_data.column_widths;
                column_count = &column_data.column_count;

                let total_column_width: u16 = widths.iter().sum();
                if rect.width < total_column_width - column_count.as_u16() {
                    column_spacing = 0;
                } else {
                    column_spacing = (rect.width <