shellcaster 2.0.1

A terminal-based podcast manager to subscribe to and play podcasts.
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use std::cmp::min;
use std::collections::hash_map::Entry;

use crossterm::style::{self, Stylize};

use super::{Panel, Scroll};
use crate::types::*;

/// Generic struct holding details about a list menu. These menus are
/// contained by the UI, and hold the list of podcasts or podcast
/// episodes. They also hold the Panel used to draw all elements to the
/// screen.
///
/// * `header` is an optional String of text that is printed above the
///   menu; the scrollable menu effectively starts below the header.
/// * `start_row` indicates the first row that is used for the menu;
///   this will be 0 if there is no header; otherwise, `start_row` will
///   be the first row below the header. Calculated relative to the
///   panel, i.e., a value between 0 and (n_row - 1)
/// * `top_row` indicates the top line of text that is shown on screen
///   (since the list of items can be longer than the available size of
///   the screen). `top_row` is calculated relative to the `items` index,
///   i.e., it will be a value between 0 and items.len()
/// * `selected` indicates which item on screen is currently highlighted.
///   It is calculated relative to the panel, i.e., a value between
///   0 and (n_row - 1)
/// * `active` indicates whether the menu is currently interactive, e.g.,
///   if the user scrolls up or down, this is the menu that will receive
///   those events.
#[derive(Debug)]
pub struct Menu<T>
where T: Clone + Menuable
{
    pub panel: Panel,
    pub header: Option<String>,
    pub items: LockVec<T>,
    pub start_row: u16, // beginning of first row of menu
    pub top_row: u16,   // top row of text shown in window
    pub selected: u16,  // which line of text is highlighted
    pub active: bool,
}

impl<T: Clone + Menuable> Menu<T> {
    /// Creates a new menu.
    pub fn new(panel: Panel, header: Option<String>, items: LockVec<T>) -> Self {
        return Self {
            panel: panel,
            header: header,
            items: items,
            start_row: 0,
            top_row: 0,
            selected: 0,
            active: false,
        };
    }

    /// Clears the terminal, and then prints the list of visible items
    /// to the terminal.
    pub fn redraw(&mut self) {
        self.panel.redraw();
        self.update_items();
    }

    /// Prints the list of visible items to the terminal.
    pub fn update_items(&mut self) {
        self.start_row = self.print_header();
        if self.selected < self.start_row {
            self.selected = self.start_row;
        }

        let (map, _, order) = self.items.borrow();
        if !order.is_empty() {
            // update selected item if list has gotten shorter
            let current_selected = self.get_menu_idx(self.selected);
            let list_len = order.len();
            if current_selected >= list_len {
                self.selected = (self.selected as usize - (current_selected - list_len) - 1) as u16;
            }

            // for visible rows, print strings from list
            for i in self.start_row..self.panel.get_rows() {
                if let Some(elem_id) = order.get(self.get_menu_idx(i)) {
                    let elem = map.get(elem_id).expect("Could not retrieve menu item.");

                    if i == self.selected || !elem.is_played() {
                        let style = if !elem.is_played() {
                            style::ContentStyle::new()
                                .with(self.panel.colors.bold.0)
                                .on(self.panel.colors.bold.1)
                                .attribute(style::Attribute::Bold)
                        } else {
                            style::ContentStyle::new()
                                .with(self.panel.colors.normal.0)
                                .on(self.panel.colors.normal.1)
                        };
                        self.panel.write_line(
                            i,
                            elem.get_title(self.panel.get_cols() as usize),
                            Some(style),
                        );
                    } else {
                        self.panel.write_line(
                            i,
                            elem.get_title(self.panel.get_cols() as usize),
                            None,
                        );
                    }
                } else {
                    break;
                }
            }
        }
    }

    /// If a header exists, prints lines of text to the panel to appear
    /// above the menu.
    fn print_header(&mut self) -> u16 {
        if let Some(header) = &self.header {
            return self.panel.write_wrap_line(0, header, None) + 2;
        } else {
            return 0;
        }
    }

    /// Scrolls the menu up or down by `lines` lines.
    ///
    /// This function examines the new selected value, ensures it does
    /// not fall out of bounds, and then updates the panel to
    /// represent the new visible list.
    pub fn scroll(&mut self, lines: Scroll) {
        let list_len = self.items.len(true) as u16;
        if list_len == 0 {
            return;
        }

        match lines {
            Scroll::Up(v) => {
                let selected_adj = self.selected - self.start_row;
                if v <= selected_adj {
                    self.unhighlight_item(self.selected);
                    self.selected -= v;
                } else {
                    let list_scroll_amount = v - selected_adj;
                    if let Some(top) = self.top_row.checked_sub(list_scroll_amount) {
                        self.top_row = top;
                    } else {
                        self.top_row = 0;
                    }
                    self.selected = self.start_row;
                    self.panel.clear_inner();
                    self.update_items();
                }
                self.highlight_item(self.selected, self.active);
            }
            Scroll::Down(v) => {
                if self.get_menu_idx(self.selected) >= list_len as usize - 1 {
                    // we're at the bottom of the list
                    return;
                }

                let n_row = self.panel.get_rows();
                let select_max = if list_len < n_row - self.start_row {
                    self.start_row + list_len - 1
                } else {
                    n_row - 1
                };

                if v <= (select_max - self.selected) {
                    self.unhighlight_item(self.selected);
                    self.selected += v;
                } else {
                    let list_scroll_amount = v - (n_row - self.selected - 1);
                    let visible_rows = n_row - self.start_row;
                    // can't scroll list if list is shorter than full screen
                    if list_len > visible_rows {
                        self.top_row =
                            min(self.top_row + list_scroll_amount, list_len - visible_rows);
                    }
                    self.selected = select_max;
                    self.panel.clear_inner();
                    self.update_items();
                }
                self.highlight_item(self.selected, self.active);
            }
        }
    }

    /// Highlights the item in the menu, given a y-value.
    pub fn highlight_item(&mut self, item_y: u16, active: bool) {
        // if list is empty, will return None
        let el_details = self
            .items
            .map_single_by_index(self.get_menu_idx(item_y), |el| {
                (el.get_title(self.panel.get_cols() as usize), el.is_played())
            });

        if let Some((title, is_played)) = el_details {
            let mut style = style::ContentStyle::new();
            if active {
                style = style.with(self.panel.colors.highlighted_active.0).on(self
                    .panel
                    .colors
                    .highlighted_active
                    .1);
            } else {
                style =
                    style
                        .with(self.panel.colors.highlighted.0)
                        .on(self.panel.colors.highlighted.1);
            }
            style = if is_played {
                style.attribute(style::Attribute::NormalIntensity)
            } else {
                style.attribute(style::Attribute::Bold)
            };
            self.panel.write_line(item_y, title, Some(style));
        }
    }

    /// Removes highlight on the item in the menu, given a y-value.
    pub fn unhighlight_item(&mut self, item_y: u16) {
        // if list is empty, will return None
        let el_details = self
            .items
            .map_single_by_index(self.get_menu_idx(item_y), |el| {
                (el.get_title(self.panel.get_cols() as usize), el.is_played())
            });

        if let Some((title, is_played)) = el_details {
            let style = if is_played {
                style::ContentStyle::new()
                    .with(self.panel.colors.normal.0)
                    .on(self.panel.colors.normal.1)
            } else {
                style::ContentStyle::new()
                    .with(self.panel.colors.bold.0)
                    .on(self.panel.colors.bold.1)
                    .attribute(style::Attribute::Bold)
            };
            self.panel.write_line(item_y, title, Some(style));
        }
    }

    /// Highlights the currently selected item in the menu, based on
    /// whether the menu is currently active or not.
    pub fn highlight_selected(&mut self) {
        self.highlight_item(self.selected, self.active);
    }

    /// Controls how the window changes when it is active (i.e.,
    /// available for user input to modify state).
    pub fn activate(&mut self) {
        self.active = true;
        self.highlight_selected();
    }

    /// Updates window size.
    pub fn resize(&mut self, n_row: u16, n_col: u16, start_x: u16) {
        self.panel.resize(n_row, n_col, start_x);
        let n_row = self.panel.get_rows();

        // if resizing moves selected item off screen, scroll the list
        // upwards to keep same item selected
        if self.selected > (n_row - 1) {
            self.top_row = self.top_row + self.selected - (n_row - 1);
            self.selected = n_row - 1;
        }
        self.redraw();
    }

    /// Given a row on the panel, this translates it into the
    /// corresponding menu item it represents. Note that this does not
    /// do any checks to ensure `screen_y` is between 0 and `n_rows`,
    /// or that the resulting menu index is between 0 and `n_items`.
    /// It's merely a straight translation.
    pub fn get_menu_idx(&self, screen_y: u16) -> usize {
        return (self.top_row + screen_y - self.start_row) as usize;
    }
}


impl Menu<Podcast> {
    /// Returns a cloned reference to the list of episodes from the
    /// currently selected podcast.
    pub fn get_episodes(&self) -> LockVec<Episode> {
        let index = self.get_menu_idx(self.selected);
        let (borrowed_map, _, borrowed_order) = self.items.borrow();
        let pod_id = borrowed_order
            .get(index)
            .expect("Could not retrieve podcast.");
        return borrowed_map
            .get(pod_id)
            .expect("Could not retrieve podcast info.")
            .episodes
            .clone();
    }

    /// Controls how the window changes when it is inactive (i.e., not
    /// available for user input to modify state).
    pub fn deactivate(&mut self) {
        self.active = false;
        self.highlight_item(self.selected, false);
    }
}

impl Menu<Episode> {
    /// Controls how the window changes when it is inactive (i.e., not
    /// available for user input to modify state). If true,
    /// `keep_highlighted` will switch the currently selected item to
    /// the "highlighted" cursor style (as opposed to the
    /// "highlighted_active" style).
    pub fn deactivate(&mut self, keep_highlighted: bool) {
        self.active = false;
        if keep_highlighted {
            self.highlight_item(self.selected, false);
        } else {
            self.unhighlight_item(self.selected);
        }
    }
}

impl Menu<NewEpisode> {
    /// Changes the status of the currently highlighted episode -- if it
    /// was selected to be downloaded, it will be unselected, and vice
    /// versa.
    pub fn select_item(&mut self) {
        let changed = self.change_item_selections(vec![self.get_menu_idx(self.selected)], None);
        if changed {
            self.update_items();
            self.highlight_selected();
        }
    }

    /// Changes the status of all items in the list. If there are any
    /// unselected episodes, this will convert all episodes to be
    /// selected; if all are selected already, only then will it convert
    /// all to unselected.
    pub fn select_all_items(&mut self) {
        let all_selected = self.items.map(|ep| ep.selected, false).iter().all(|x| *x);
        let changed =
            self.change_item_selections((0..self.items.len(false)).collect(), Some(!all_selected));
        if changed {
            self.update_items();
            self.highlight_selected();
        }
    }

    /// Given a list of index values in the menu, this changes the status
    /// of these episode -- if they were selected to be downloaded, they
    /// will be unselected, and vice versa. If `selection` is a boolean,
    /// however, it will be set to this value explicitly rather than just
    /// being reversed.
    fn change_item_selections(&mut self, indexes: Vec<usize>, selection: Option<bool>) -> bool {
        let mut changed = false;
        {
            let (mut borrowed_map, borrowed_order, _) = self.items.borrow();
            for idx in indexes {
                if let Some(ep_id) = borrowed_order.get(idx) {
                    if let Entry::Occupied(mut ep) = borrowed_map.entry(*ep_id) {
                        let ep = ep.get_mut();
                        match selection {
                            Some(sel) => ep.selected = sel,
                            None => ep.selected = !ep.selected,
                        }
                        changed = true;
                    }
                }
            }
        }
        return changed;
    }
}


// TESTS ----------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use std::rc::Rc;

    fn create_menu(n_row: u16, n_col: u16, top_row: u16, selected: u16) -> Menu<Episode> {
        let colors = Rc::new(crate::ui::AppColors::default());
        let titles = vec![
            "A Very Cool Episode",
            "This is a very long episode title but we'll get through it together",
            "An episode with le Unicodé",
            "How does an episode with emoji sound? 😉",
            "Here's another title",
            "Un titre, c'est moi!",
            "One more just for good measure",
        ];
        let mut items = Vec::new();
        for (i, t) in titles.iter().enumerate() {
            let played = i % 2 == 0;
            items.push(Episode {
                id: i as _,
                pod_id: 1,
                title: t.to_string(),
                url: String::new(),
                guid: String::new(),
                description: String::new(),
                pubdate: Some(Utc::now()),
                duration: Some(12345),
                path: None,
                played: played,
            });
        }

        let panel = Panel::new(
            "Episodes".to_string(),
            1,
            colors.clone(),
            n_row,
            n_col,
            0,
            (0, 0, 0, 0),
        );
        return Menu {
            panel: panel,
            header: None,
            items: LockVec::new(items),
            start_row: 0,
            top_row: top_row,
            selected: selected,
            active: true,
        };
    }

    #[test]
    fn scroll_up() {
        let real_rows = 5;
        let real_cols = 65;
        let mut menu = create_menu(real_rows + 2, real_cols + 3, 2, 0);
        menu.update_items();

        menu.scroll(Scroll::Up(1));

        let expected_top = menu
            .items
            .map_single_by_index(1, |ep| ep.get_title(real_cols as usize))
            .unwrap();
        let expected_bot = menu
            .items
            .map_single_by_index(5, |ep| ep.get_title(real_cols as usize))
            .unwrap();

        assert_eq!(menu.panel.get_row(0), expected_top);
        assert_eq!(menu.panel.get_row(4), expected_bot);
    }

    #[test]
    fn scroll_down() {
        let real_rows = 5;
        let real_cols = 65;
        let mut menu = create_menu(real_rows + 2, real_cols + 3, 0, 4);
        menu.update_items();

        menu.scroll(Scroll::Down(1));

        let expected_top = menu
            .items
            .map_single_by_index(1, |ep| ep.get_title(real_cols as usize))
            .unwrap();
        let expected_bot = menu
            .items
            .map_single_by_index(5, |ep| ep.get_title(real_cols as usize))
            .unwrap();

        assert_eq!(menu.panel.get_row(0), expected_top);
        assert_eq!(menu.panel.get_row(4), expected_bot);
    }

    #[test]
    fn resize_bigger() {
        let real_rows = 5;
        let real_cols = 65;
        let mut menu = create_menu(real_rows + 2, real_cols + 3, 0, 4);
        menu.update_items();

        menu.resize(real_rows + 2 + 5, real_cols + 3 + 5, 0);
        menu.update_items();

        assert_eq!(menu.top_row, 0);
        assert_eq!(menu.selected, 4);

        let non_empty: Vec<String> = menu
            .panel
            .buffer
            .iter()
            .filter_map(|x| if x.is_empty() { None } else { Some(x.clone()) })
            .collect();
        assert_eq!(non_empty.len(), menu.items.len(true));
    }

    #[test]
    fn resize_smaller() {
        let real_rows = 7;
        let real_cols = 65;
        let mut menu = create_menu(real_rows + 2, real_cols + 3, 0, 6);
        menu.update_items();

        menu.resize(real_rows + 2 - 2, real_cols + 3 - 5, 0);
        menu.update_items();

        assert_eq!(menu.top_row, 2);
        assert_eq!(menu.selected, 4);

        let non_empty: Vec<String> = menu
            .panel
            .buffer
            .iter()
            .filter_map(|x| if x.is_empty() { None } else { Some(x.clone()) })
            .collect();
        assert_eq!(non_empty.len(), (real_rows - 2) as usize);
    }

    #[test]
    fn chop_accent() {
        let real_rows = 5;
        let real_cols = 25;
        let mut menu = create_menu(real_rows + 2, real_cols + 5, 0, 0);
        menu.update_items();

        let expected = " An episode with le Unicod ".to_string();

        assert_eq!(menu.panel.get_row(2), expected);
    }

    #[test]
    fn chop_emoji() {
        let real_rows = 5;
        let real_cols = 38;
        let mut menu = create_menu(real_rows + 2, real_cols + 5, 0, 0);
        menu.update_items();

        let expected = " How does an episode with emoji sound?  ".to_string();

        assert_eq!(menu.panel.get_row(3), expected);
    }
}