summaryrefslogtreecommitdiffstats
path: root/src/display/components/table.rs
blob: 2b450b1f62c07f5f9535b909328870c3dd129035 (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
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
use std::{collections::HashMap, fmt, net::IpAddr, ops::Index, rc::Rc};

use derivative::Derivative;
use itertools::Itertools;
use ratatui::{
    layout::{Constraint, Rect},
    style::{Color, Style},
    terminal::Frame,
    widgets::{Block, Borders, Row},
};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

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

/// The displayed layout choice of a table.
/// Each value in the array is the width of each column.
///
/// Note that this only determines how a table is displayed, not what data it contains.
///
/// If we intend to display different number of columns in the future,
/// then new variants should be added.
#[derive(Copy, Clone, Debug)]
pub enum DisplayLayout {
    /// Show 2 columns.
    C2([u16; 2]),
    /// Show 3 columns.
    C3([u16; 3]),
}
impl Index<usize> for DisplayLayout {
    type Output = u16;

    fn index(&self, i: usize) -> &Self::Output {
        match self {
            Self::C2(arr) => &arr[i],
            Self::C3(arr) => &arr[i],
        }
    }
}
impl DisplayLayout {
    #[inline]
    fn columns_count(&self) -> usize {
        match self {
            Self::C2(_) => 2,
            Self::C3(_) => 3,
        }
    }
    #[inline]
    fn iter(&self) -> impl Iterator<Item = &u16> {
        match self {
            Self::C2(ws) => ws.iter(),
            Self::C3(ws) => ws.iter(),
        }
    }
    #[inline]
    fn widths_sum(&self) -> u16 {
        self.iter().sum()
    }
    /// Returns the computed actual width and the spacer width.
    ///
    /// See [`Table`] for layout rules.
    fn compute_actual_widths(&self, available: u16) -> (Self, u16) {
        let columns_count = self.columns_count() as u16;
        let desired_min = self.widths_sum();

        // spacer max width is 2
        let spacer = if available > desired_min {
            ((available - desired_min) / (columns_count - 1)).min(2)
        } else {
            0
        };
        let available_without_spacers = available - spacer * (columns_count - 1);

        // multiplier
        let m = available_without_spacers as f64 / desired_min as f64;

        // remainder width is arbitrarily given to column 0
        let computed = match *self {
            Self::C2([_w0, w1]) => {
                let w1_new = (w1 as f64 * m).trunc() as u16;
                Self::C2([available_without_spacers - w1_new, w1_new])
            }
            Self::C3([_w0, w1, w2]) => {
                let w1_new = (w1 as f64 * m).trunc() as u16;
                let w2_new = (w2 as f64 * m).trunc() as u16;
                Self::C3([available_without_spacers - w1_new - w2_new, w1_new, w2_new])
            }
        };

        (computed, spacer)
    }
}

/// All data of a table.
///
/// If tables with different number of columns are added in the future,
/// then new variants should be added.
#[derive(Clone, Debug)]
enum TableData {
    /// A table with 3 columns.
    C3(NColsTableData<3>),
}
impl From<NColsTableData<3>> for TableData {
    fn from(data: NColsTableData<3>) -> Self {
        Self::C3(data)
    }
}
impl TableData {
    fn column_names(&self) -> &[&str] {
        match self {
            Self::C3(inner) => &inner.column_names,
        }
    }
    fn rows(&self) -> Vec<&[String]> {
        match self {
            Self::C3(inner) => inner.rows.iter().map(|r| r.as_slice()).collect(),
        }
    }
    fn column_selector(&self) -> &dyn Fn(&DisplayLayout) -> Vec<usize> {
        match self {
            Self::C3(inner) => inner.column_selector.as_ref(),
        }
    }
}

/// All data of a table with `C` columns.
///
/// Note that the number of columns here is independent of the number of columns
/// being actually shown. If width-constrained, we might only show some of the columns.
#[derive(Clone, Derivative)]
#[derivative(Debug)]
struct NColsTableData<const C: usize> {
    /// The name of each column.
    column_names: [&'static str; C],
    /// All rows of data.
    rows: Vec<[String; C]>,
    /// Function to determine which columns to show for a given layout.
    ///
    /// This function should return a vector of column indices.
    /// The indices should be less than `C`; otherwise this will cause a runtime panic.
    #[derivative(Debug(format_with = "debug_fn::<C>"))]
    column_selector: Rc<ColumnSelectorFn>,
}

/// Clippy wanted me to write this. 💢
type ColumnSelectorFn = dyn Fn(&DisplayLayout) -> Vec<usize>;

fn debug_fn<const C: usize>(
    _func: &Rc<ColumnSelectorFn>,
    f: &mut fmt::Formatter,
) -> Result<(), fmt::Error> {
    write!(f, "Rc</* function pointer */>")
}

/// A table displayed by bandwhich.
#[derive(Clone, Debug)]
pub struct Table {
    title: &'static str,
    /// A layout mapping between minimum available width and the width of each column.
    ///
    /// Note that the width of each column here is the "desired minimum width".
    ///
    /// - Wt = available width of table
    /// - Wd = sum of desired minimum width of each column
    ///
    /// - If `Wt >= Wd`, spacers with a maximum width of `2` will be inserted
    ///   between columns; and then the columns will proportionally expand.
    /// - If `Wt < Wd`, columns will proportionally shrink.
    width_cutoffs: Vec<(u16, DisplayLayout)>,
    data: TableData,
}
impl Table {
    pub fn create_connections_table(state: &UIState, ip_to_host: &HashMap<IpAddr, String>) -> Self {
        use DisplayLayout as D;

        let title = "Utilization by connection";
        let width_cutoffs = vec![
            (0, D::C2([32, 18])),
            (80, D::C3([36, 12, 18])),
            (100, D::C3([54, 18, 22])),
            (120, D::C3([72, 24, 22])),
        ];

        let column_names = [
            "Connection",
            "Process",
            if state.cumulative_mode {
                "Data (Up / Down)"
            } else {
                "Rate (Up / Down)"
            },
        ];
        let rows = state
            .connections
            .iter()
            .map(|(connection, connection_data)| {
                [
                    display_connection_string(
                        connection,
                        ip_to_host,
                        &connection_data.interface_name,
                    ),
                    connection_data.process_name.to_string(),
                    display_upload_and_download(
                        connection_data,
                        state.unit_family,
                        state.cumulative_mode,
                    ),
                ]
            })
            .collect();
        let column_selector = Rc::new(|layout: &D| match layout {
            D::C2(_) => vec![0, 2],
            D::C3(_) => vec![0, 1, 2],
        });

        Table {
            title,
            width_cutoffs,
            data: NColsTableData {
                column_names,
                rows,
                column_selector,
            }
            .into(),
        }
    }

    pub fn create_processes_table(state: &UIState) -> Self {
        use DisplayLayout as D;

        let title = "Utilization by process name";
        let width_cutoffs = vec![
            (0, D::C2([16, 18])),
            (50, D::C3([16, 12, 20])),
            (60, D::C3([24, 12, 20])),
            (80, D::C3([36,