summaryrefslogtreecommitdiffstats
path: root/src/canvas/drawing_utils.rs
blob: ee21660aeb8f5d3f73f202b6052c05453854c49c (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
use tui::layout::Rect;

use crate::app::{self};
use std::{
    cmp::{max, min},
    time::Instant,
};

/// Return a (hard)-width vector for column widths.
///
/// * `total_width` is the, well, total width available.  **NOTE:** This function automatically
/// takes away 2 from the width as part of the left/right
/// bounds.
/// * `hard_widths` is inflexible column widths.  Use a `None` to represent a soft width.
/// * `soft_widths_min` is the lower limit for a soft width.  Use `None` if a hard width goes there.
/// * `soft_widths_max` is the upper limit for a soft width, in percentage of the total width.  Use
///   `None` if a hard width goes there.
/// * `soft_widths_desired` is the desired soft width.  Use `None` if a hard width goes there.
/// * `left_to_right` is a boolean whether to go from left to right if true, or right to left if
///   false.
///
/// **NOTE:** This function ASSUMES THAT ALL PASSED SLICES ARE OF THE SAME SIZE.
///
/// **NOTE:** The returned vector may not be the same size as the slices, this is because including
/// 0-constraints breaks tui-rs.
pub fn get_column_widths(
    total_width: u16, hard_widths: &[Option<u16>], soft_widths_min: &[Option<u16>],
    soft_widths_max: &[Option<f64>], soft_widths_desired: &[Option<u16>], left_to_right: bool,
) -> Vec<u16> {
    debug_assert!(
        hard_widths.len() == soft_widths_min.len(),
        "hard width length != soft width min length!"
    );
    debug_assert!(
        soft_widths_min.len() == soft_widths_max.len(),
        "soft width min length != soft width max length!"
    );
    debug_assert!(
        soft_widths_max.len() == soft_widths_desired.len(),
        "soft width max length != soft width desired length!"
    );

    if total_width > 2 {
        let initial_width = total_width - 2;
        let mut total_width_left = initial_width;
        let mut column_widths: Vec<u16> = vec![0; hard_widths.len()];
        let range: Vec<usize> = if left_to_right {
            (0..hard_widths.len()).collect()
        } else {
            (0..hard_widths.len()).rev().collect()
        };

        for itx in &range {
            if let Some(Some(hard_width)) = hard_widths.get(*itx) {
                // Hard width...
                let space_taken = min(*hard_width, total_width_left);

                // TODO [COLUMN MOVEMENT]: Remove this
                if *hard_width > space_taken {
                    break;
                }

                column_widths[*itx] = space_taken;
                total_width_left -= space_taken;
                total_width_left = total_width_left.saturating_sub(1);
            } else if let (
                Some(Some(soft_width_max)),
                Some(Some(soft_width_min)),
                Some(Some(soft_width_desired)),
            ) = (
                soft_widths_max.get(*itx),
                soft_widths_min.get(*itx),
                soft_widths_desired.get(*itx),
            ) {
                // Soft width...
                let soft_limit = max(
                    if soft_width_max.is_sign_negative() {
                        *soft_width_desired
                    } else {
                        (*soft_width_max * initial_width as f64).ceil() as u16
                    },
                    *soft_width_min,
                );
                let space_taken = min(min(soft_limit, *soft_width_desired), total_width_left);

                // TODO [COLUMN MOVEMENT]: Remove this
                if *soft_width_min > space_taken {
                    break;
                }

                column_widths[*itx] = space_taken;
                total_width_left -= space_taken;
                total_width_left = total_width_left.saturating_sub(1);
            }
        }

        while let Some(0) = column_widths.last() {
            column_widths.pop();
        }

        if !column_widths.is_empty() {
            // Redistribute remaining.
            let amount_per_slot = total_width_left / column_widths.len() as u16;
            total_width_left %= column_widths.len() as u16;
            for (index, width) in column_widths.iter_mut().enumerate() {
                if index < total_width_left.into() {
                    *width += amount_per_slot + 1;
                } else {
                    *width += amount_per_slot;
                }
            }
        }

        column_widths
    } else {
        vec![]
    }
}

pub fn get_search_start_position(
    num_columns: usize, cursor_direction: &app::CursorDirection, cursor_bar: &mut usize,
    current_cursor_position: usize, is_force_redraw: bool,
) -> usize {
    if is_force_redraw {
        *cursor_bar = 0;
    }

    match cursor_direction {
        app::CursorDirection::Right => {
            if current_cursor_position < *cursor_bar + num_columns {
                // If, using previous_scrolled_position, we can see the element
                // (so within that and + num_rows) just reuse the current previously scrolled position
                *cursor_bar
            } else if current_cursor_position >= num_columns {
                // Else if the current position past the last element visible in the list, omit
                // until we can see that element
                *cursor_bar = current_cursor_position - num_columns;
                *cursor_bar
            } else {
                // Else, if it is not past the last element visible, do not omit anything
                0
            }
        }
        app::CursorDirection::Left => {
            if current_cursor_position <= *cursor_bar {
                // If it's past the first element, then show from that element downwards
                *cursor_bar = current_cursor_position;
            } else if current_cursor_position >= *cursor_bar + num_columns {
                *cursor_bar = current_cursor_position - num_columns;
            }
            // Else, don't change what our start position is from whatever it is set to!
            *cursor_bar
        }
    }
}

pub fn get_start_position(
    num_rows: usize, scroll_direction: &app::ScrollDirection, scroll_position_bar: &mut usize,
    currently_selected_position: usize, is_force_redraw: bool,
) -> usize {
    if is_force_redraw {
        *scroll_position_bar = 0;
    }

    // FIXME: Note that num_rows is WRONG here! It assumes the number of rows - 1... oops.

    match scroll_direction {
        app::ScrollDirection::Down => {
            if currently_selected_position < *scroll_position_bar + num_rows {
                // If, using previous_scrolled_position, we can see the element
                // (so within that and + num_rows) just reuse the current previously scrolled position
                *scroll_position_bar
            } else if currently_selected_position >= num_rows {
                // Else if the current position past the last element visible in the list, omit
                // until we can see that element
                *scroll_position_bar = currently_selected_position - num_rows;
                *scroll_position_bar
            } else {
                // Else, if it is not past the last element visible, do not omit anything
                0
            }
        }
        app::ScrollDirection::Up => {
            if currently_selected_position <= *scroll_position_bar {
                // If it's past the first element, then show from that element downwards
                *scroll_position_bar = currently_selected_position;
            } else if currently_selected_position >= *scroll_position_bar + num_rows {
                *scroll_position_bar = currently_selected_position - num_rows;
            }
            // Else, don't change what our start position is from whatever it is set to!
            *scroll_position_bar
        }
    }
}

/// Calculate how many bars are to be drawn within basic mode's components.
pub fn calculate_basic_use_bars(use_percentage: f64, num_bars_available: usize) -> usize {
    std::cmp::min(
        (num_bars_available as f64 * use_percentage / 100.0).round() as usize,
        num_bars_available,
    )
}

/// Determine whether a graph x-label should be hidden.
pub fn should_hide_x_label(
    always_hide_time: bool, autohide_time: bool, timer: &mut Option<Instant>, draw_loc: Rect,
) -> bool {
    use crate::constants::*;

    if always_hide_time || (autohide_time && timer.is_none()) {
        true
    } else if let Some(time) = timer {
        if Instant::now().duration_since(*time).as_millis() < AUTOHIDE_TIMEOUT_MILLISECONDS.into() {
            false
        } else {
            *timer = None;
            true
        }
    } else {
        draw_loc.height < TIME_LABEL_HEIGHT_LIMIT
    }
}

#[cfg(test)]
mod test {

    use super::*;

    #[test]
    fn test_get_start_position() {
        use crate::app::ScrollDirection::{self, Down, Up};

        fn test(
            bar: usize, num: usize, direction: ScrollDirection, selected: usize, force: bool,
            expected_posn: usize, expected_bar: usize,
        ) {
            let mut bar = bar;
            assert_eq!(
                get_start_position(num, &direction, &mut bar, selected, force),
                expected_posn
            );
            assert_eq!(bar, expected_bar);
        }

        // Scrolling down from start
        test(0, 10, Down, 0, false, 0