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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! # youchoose
//!
//! A simple, easy to use command line menu for Rust.
//!
//!
//!
//! ## Usage
//!
//! There are two methods you need to be familiar with to get started:
//! `Menu::new` which takes an `Iterator` as an argument, and `Menu::show`
//! which initializes `ncurses` and displays the menu.
//!
//! Here is a minimal example that displays the range  `0..100` in a menu:
//!
//! ```rust
//! use youchoose;
//!
//! fn main() {
//!     let mut menu = youchoose::Menu::new(0..100);
//!     let choice = menu.show();
//!     // `choice` is a Vec<usize> containing the chosen indices
//!     println!("Index of the chosen item: {:?}", choice);
//! }
//! ```
//!
//! ![basic config](https://raw.githubusercontent.com/nathom/youchoose/main/screenshots/basic.png)
//!
//! Either `↓↑` or `jk` can be used to scroll, and `return` is used to select.
//! `ESC` or `q` can be used to quit.
//!
//! **Previews**
//!
//! The `youchoose::Menu` has a preview feature, which executes a command and
//! shows the results on a seperate pane.
//!
//! ```rust
//! use youchoose;
//!
//! fn main(){
//!     let mut menu = youchoose::Menu::new(0..100)
//!     .preview(multiples);
//!     let choice = menu.show();
//!     println!("Chose {:?}", choice);
//!     
//! }
//!
//! fn multiples(num: i32) -> String {
//!     let mut buffer = String::new();
//!     for i in 0..20 {
//!         buffer.push_str(
//!             &format!("{} times {} is equal to {}!\n", num, i, num * i)
//!         );
//!     }
//!     buffer
//! }
//! ```
//!
//! ![preview](https://raw.githubusercontent.com/nathom/youchoose/main/screenshots/with_preview.png)
//!
//! **Customization**
//!
//! Let's take a look at an example that showcases the available methods for customization.
//!
//! ```rust
//! use youchoose;
//!
//! fn main() {
//!     let mut menu = youchoose::Menu::new(0..100)
//!         .preview(multiples)              // Sets the preview function
//!         .preview_pos(youchoose::ScreenSide::Bottom, 0.3)  // Sets the position of the preview pane
//!         .preview_label(" multiples ".to_string())    // Sets the text at the top of the preview pane
//!         .multiselect()                   // Allows multiple items to be selected
//!         .icon(":(")                      // Sets the default (not selected) icon for an item
//!         .selected_icon(":)")             // The icon for selected items
//!         .add_multiselect_key('s' as i32) // Bind the 's' key to multiselect
//!         .add_up_key('u' as i32)          // Bind the 'u' key to up
//!         .add_down_key('d' as i32)        // Bind the 'd' key to down
//!         .add_select_key('.' as i32);     // Bind the '.' key to select
//!
//!     let choice = menu.show();
//! }
//!
//! fn multiples(num: i32) -> String {
//!     // --- Snip ---
//! }
//! ```
//!
//! ![fully customized](https://raw.githubusercontent.com/nathom/youchoose/main/screenshots/customized.png)

use std::fmt;
// use std::fs::OpenOptions;
// use std::io::Write;
use std::iter::Peekable;
use std::ops;

use ncurses::*;

/// A Menu that lazily displays an iterable and (optionally) its preview.
pub struct Menu<'a, I, D>
where
    D: fmt::Display,
    I: Iterator<Item = D>,
{
    iter: Peekable<I>,
    screen: Screen,
    preview: Option<Preview<D>>,
    item_icon: &'a str,
    chosen_item_icon: &'a str,
    selection: Vec<usize>,
    keys: Keys,

    state: MenuState<'a>,
    config: MenuConfig,
}

enum MenuReturnCode {
    Done,
    Pass,
}
use MenuReturnCode::{Done, Pass};
type RetCode = MenuReturnCode;

impl<'a, I, D> Menu<'a, I, D>
where
    D: fmt::Display,
    I: Iterator<Item = D>,
{
    /// Create a new menu object. The iterable passed in must contain displayable
    /// items.
    pub fn new(iter: I) -> Menu<'a, I, D> {
        let screen = Screen::new(ScreenSide::Full, 0.5);

        let item_icon: &'a str = "❯";
        let chosen_item_icon: &'a str = "*";

        Menu {
            iter: iter.peekable(),
            screen,
            preview: None,
            item_icon: &item_icon,
            chosen_item_icon: &chosen_item_icon,
            selection: Vec::new(),

            keys: Keys {
                down: vec![KEY_DOWN, 'j' as i32],
                up: vec![KEY_UP, 'k' as i32],
                select: vec![10],
                multiselect: vec![32],
            },

            state: MenuState {
                hover: 0,
                start: 0,
                items: Vec::new(),
            },

            config: MenuConfig { multiselect: false },
        }
    }

    /// Initialize curses and display the menu on the screen.
    pub fn show(&mut self) -> Vec<usize> {
        init_curses();

        self.screen.show();
        if let Some(prev) = &mut self.preview {
            prev.show();
        }
        self.refresh();

        loop {
            match self.screen.get_key() {
                27 | 113 => break, // ESC or q

                val => {
                    // This will erase the entire window
                    self.screen.erase();

                    match self.handle_key(val) {
                        Pass => {
                            self.refresh();
                        }
                        Done => break,
                    }
                }
            }
        }

        end_curses();
        self.finish()
    }

    fn finish(&self) -> Vec<usize> {
        self.selection.clone()
    }

    fn yield_item(&mut self, i: usize) -> Option<&Item> {
        while self.state.items.len() <= i {
            if let Some(item) = self.iter.next() {
                let mut new_item =
                    Item::new(&item, self.item_icon, self.chosen_item_icon);
                if let Some(preview) = &self.preview {
                    new_item.preview(item, &preview.func);
                }
                self.state.items.push(new_item);
            } else {
                return None;
            }
        }
        Some(&self.state.items[i])
    }

    fn refresh(&mut self) {
        // Maximum index that will fit on current screen state
        let end = self.state.start + self.screen.max_y();
        self.yield_item(end);

        self.screen.reset_pos();
        if let Some(prev) = &mut self.preview {
            prev.draw_box();
            prev.screen.reset_pos();
        }
        let mut i = self.state.start;
        let pos = self.state.hover + i;
        loop {
            if let Some(item) = self.state.items.get(i) {
                if !self.screen.write_item(&item, pos == i) {
                    break;
                }
                if pos == i {
                    if let Some(prev) = &mut self.preview {
                        prev.screen.addstr(item.preview.as_ref().unwrap());
                    }
                }

                i += 1;
            } else {
                break;
            }
        }

        self.screen.refresh();

        if let Some(prev) = &mut self.preview {
            prev.refresh();
        }
    }

    fn handle_key(&mut self, val: i32) -> RetCode {
        if self.keys.down.contains(&val) {
            self.move_selection(1)
        } else if self.keys.up.contains(&val) {
            self.move_selection(-1)
        } else if self.config.multiselect
            && self.keys.multiselect.contains(&val)
        {
            self.multiselect_item()
        } else if self.keys.select.contains(&val) {
            self.select_item()
        } else {
            Pass
        }
    }

    fn select_item(&mut self) -> RetCode {
        let curr_item_idx = self.state.start + self.state.hover;
        match self.selection.last() {
            Some(&num) if num == curr_item_idx => return Done,
            _ => (),
        }
        self.state.items[curr_item_idx].select();
        self.selection.push(curr_item_idx);
        Done
    }

    fn multiselect_item(&mut self) -> RetCode {
        let curr_item_idx = self.state.start + self.state.hover;
        let curr_item = &mut self.state.items[curr_item_idx];
        curr_item.select();

        let item_idx_pos =
            match self.selection.iter().position(|x| *x == curr_item_idx) {
                Some(idx) => idx as i32,
                None => -1,
            };

        if curr_item.chosen() && item_idx_pos == -1 {
            self.selection.push(curr_item_idx);
        } else if !curr_item.chosen() && item_idx_pos != -1 {
            self.selection.remove(item_idx_pos as usize);
        }

        Pass
    }

    fn scroll(&mut self, amount: i32) {
        self.state.start = ((self.state.start as i32) + amount) as usize;
        assert!(self.state.start < 1_000_000);
    }

    fn move_selection(&mut self, amount: i32) -> RetCode {
        let num_items = self.screen.items_on_screen as f64;
        let new_hover = ((self.state.hover as i32) + amount) as f64;

        if new_hover < 0.0 || new_hover == num_items {
            return Pass;
        }

        self.state.hover = new_hover as usize;

        if new_hover > num_items * 0.67
            && self.state.start + self.screen.items_on_screen
                < self.state.items.len()
        {
            self.scroll(1);
            self.state.hover -= 1;
        } else if new_hover < num_items * 0.33
            && self.state.start > 0
            && amount < 0
        {
            self.scroll(-1);
            self.state.hover += 1;
        }

        Pass
    }

    /// Add a preview pane that displays the result of applying the function
    /// passed in to each item in the iterable. The function must return a
    /// String.
    pub fn preview<F>(mut self, func: F) -> Menu<'a, I, D>
    where
        F: Fn(D) -> String + 'static,
    {
        let func = DispFunc::new(Box::new(func));
        self.screen.set_pos(ScreenSide::Left, 0.5);
        self.preview = Some(Preview::new(func, ScreenSide::Right, 0.5));
        self
    }

    /// Sets the position of the preview pane. The `side` parameter determines
    /// the side on which the pane sits. The `width` parameter is a float between
    /// `0.0` and `1.0`, inclusive. It determines the proportion of the screen that
    /// the preview pane should use.
    ///
    /// The menu's side is automatically switched to opposite the preview pane's side,
    /// and the menu's width is set to `1 - width`.
    pub fn preview_pos(
        mut self,
        side: ScreenSide,
        width: f64,
    ) -> Menu<'a, I, D> {
        self.screen.set_pos(!side, 1.0 - width);
        self.preview
            .as_mut()
            .expect("Must create preview before settting it's position")
            .set_pos(side, width);

        self
    }

    /// Sets the default icon of the menu. This is displayed before each entry.
    pub fn icon(mut self, icon: &'a str) -> Menu<'a, I, D> {
        self.item_icon = icon;
        self
    }

    /// Sets the icon displayed when an item is selected in multiselect mode.
    pub fn selected_icon(mut self, icon: &'a str) -> Menu<'a, I, D> {
        self.chosen_item_icon = icon;
        self
    }

    /// Sets the text displayed on top of the preview box. It is recommended to surround the label
    /// with spaces for aesthetic reasons. If it is not set, `" preview "` will be used.
    pub fn preview_label(mut self, label: String) -> Menu<'a, I, D> {
        self.preview
            .as_mut()
            .expect("Must create preview before settting it's position")
            .set_label(label);
        self
    }

    /// Adds a keybinding that triggers a multiselection. This inputs an `ncurses` keycode.
    /// All ascii keys can be set by passing the character as an `i32`. The keycodes for
    /// special keys can be found by importing `ncurses` and using the provided constants
    /// or by testing with the `getch` function. For example, running the following will display
    /// the keycodes on the screen.
    ///
    /// ```
    /// // Make sure to add ncurses as a dependency!
    /// use ncurses::*;
    /// fn main() {
    ///     initscr();
    ///     loop {
    ///         let c: i32 = getch();
    ///         clear();
    ///         if c == 'q' as i32 {break}
    ///         addstr(&format!("Pressed key with keycode {}!", c.to_string()));
    ///     }
    ///     endwin();
    /// }
    /// ```
    pub fn add_multiselect_key(mut self, key: i32) -> Menu<'a, I, D> {
        self.keys.multiselect.push(key);
        self
    }

    /// Adds a keybinding that triggers an up movement. See [`add_multiselect_key`](struct.Menu.html#method.add_multiselect_key) for more information.
    pub fn add_up_key(mut self, key: i32) -> Menu<'a, I, D> {
        self.keys.up.push(key);
        self
    }

    /// Adds a keybinding that triggers a down movement. See [`add_multiselect_key`](struct.Menu.html#method.add_multiselect_key) for more information.
    pub fn add_down_key(mut self, key: i32) -> Menu<'a, I, D> {
        self.keys.down.push(key);
        self
    }

    /// Adds a keybinding that triggers a selection. See [`add_multiselect_key`](struct.Menu.html#method.add_multiselect_key) for more information.
    pub fn add_select_key(mut self, key: i32) -> Menu<'a, I, D> {
        self.keys.select.push(key);
        self
    }

    /// Allow multiple items to be selected from the menu.
    pub fn multiselect(mut self) -> Menu<'a, I, D> {
        self.config.multiselect = true;
        self
    }
}

struct MenuState<'a> {
    hover: usize,
    start: usize,
    items: Vec<Item<'a>>,
}

struct Keys {
    down: Vec<i32>,
    up: Vec<i32>,
    select: Vec<i32>,
    multiselect: Vec<i32>,
}

struct MenuConfig {
    multiselect: bool,
}

struct Screen {
    bounds: (Pair, Pair),
    pos: Pair,
    items_on_screen: usize,
    side: ScreenSide,
    width: f64,
}

impl Screen {
    fn new(side: ScreenSide, width: f64) -> Screen {
        assert!(width > 0.0 && width <= 1.0);

        let bounds = (Pair { y: 0, x: 0 }, Pair { y: 0, x: 0 });
        let pos = Pair { y: 0, x: 0 };

        Screen {
            bounds,
            pos,
            items_on_screen: 0,
            side,
            width,
        }
    }

    fn show(&mut self) {
        self.bounds = self
            .side
            .get_bounds((Pair { y: 0, x: 0 }, Self::get_size()), self.width);
    }

    fn write_item(&mut self, item: &Item, highlight: bool) -> bool {
        self.skiplines(1);

        if self.pos.y >= self.bounds.1.y - 1 {
            return false;
        }

        let icon_color = if item.chosen() { 3 } else { 2 };

        attron(COLOR_PAIR(icon_color));
        attron(A_BOLD());

        self.addstr(item.icon());
        self.addch(' ');

        attroff(A_BOLD());
        attroff(COLOR_PAIR(icon_color));

        if highlight {
            attron(COLOR_PAIR(1));
        }

        self.addstr(item.string());

        if highlight {
            attroff(COLOR_PAIR(1));
        }

        self.items_on_screen += 1;

        true
    }

    fn draw_box(
        &mut self,
        side: ScreenSide,
        width: f64,
        label: &Option<String>,
    ) {
        let bounds = side
            .get_bounds((self.bounds.0.clone(), self.bounds.1.clone()), width);

        let box_width = (bounds.1.x - bounds.0.x) as usize;
        // let box_height = (bounds.1.y - bounds.0.y) as usize;

        let hor_line = "─";
        let vert_line = "│";
        let corner_tl = "┌";
        let corner_bl = "└";
        let corner_tr = "┐";
        let corner_br = "┘";

        // top line
        self.pos.x = bounds.0.x;
        self.pos.y = bounds.0.y;
        self.addstr(corner_tl);
        let label_len = match label {
            Some(label) => {
                self.addstr(&label);
                label.len()
            }
            None => {
                self.addstr(" preview ");
                9
            }
        };
        self.addstr(&hor_line.repeat(box_width - label_len - 2));
        self.addstr(corner_tr);

        // vertical lines
        // accessing curses directly
        for row in bounds.0.y + 1..bounds.1.y {
            mvaddstr(row, bounds.0.x, vert_line);
            mvaddstr(row, bounds.1.x - 1, vert_line);
        }

        // bottom line
        self.pos.x = bounds.0.x;
        self.pos.y = bounds.1.y - 1;
        self.addstr(corner_bl);
        self.addstr(&hor_line.to_string().repeat(box_width - 2));
        self.addstr(corner_br);
    }

    fn get_key(&self) -> i32 {
        getch()
    }

    fn refresh(&mut self) {
        refresh();
        self.bounds = self
            .side
            .get_bounds((Pair { y: 0, x: 0 }, Self::get_size()), self.width);
    }

    fn erase(&mut self) {
        erase();
        self.bounds = self
            .side
            .get_bounds((Pair { y: 0, x: 0 }, Self::get_size()), self.width);
    }

    fn max_y(&mut self) -> usize {
        self.bounds.1.y as usize
    }

    fn _max_x(&mut self) -> usize {
        self.bounds.1.x as usize
    }

    fn reset_pos(&mut self) {
        self.pos.y = self.bounds.0.y;
        self.pos.x = self.bounds.0.x;
        self.items_on_screen = 0;
    }

    fn get_size() -> Pair {
        let mut size = Pair { y: 0, x: 0 };
        getmaxyx(stdscr(), &mut size.y, &mut size.x);
        size
    }

    fn addstr(&mut self, s: &str) {
        let screen_width = self.bounds.1.x - self.bounds.0.x;
        let mut chars = s.chars();
        let mut char_counter = 0;
        let mut curr_string = String::new();

        loop {
            let next_char = chars.next();
            if let Some(c) = next_char {
                // TODO: shorten the code here
                let mut both = false;
                if char_counter >= screen_width {
                    self.addstr_clean(&curr_string);
                    curr_string.clear();
                    self.pos.y += 1;
                    self.pos.x = self.bounds.0.x;
                    char_counter = 0;

                    both = true;
                }
                if c == '\n' {
                    self.addstr_clean(&curr_string);
                    curr_string.clear();
                    self.pos.y += 1;
                    self.pos.x = self.bounds.0.x;
                    char_counter = 0;
                    both &= true;
                    if both {
                        self.pos.y -= 1;
                    }

                    continue;
                }
                if self.pos.y >= self.bounds.1.y {
                    curr_string.clear();
                    break;
                }
                assert!(c != '\n');
                curr_string.push(c);
                char_counter += 1;
            } else {
                break;
            }
        }
        assert!(!curr_string.contains('\n'));
        self.addstr_clean(&curr_string);
    }

    fn addstr_clean(&mut self, s: &str) {
        mvaddstr(self.pos.y, self.pos.x, s);
        self.pos.x += s.char_indices().collect::<Vec<_>>().len() as i32;
    }

    fn addch(&mut self, c: char) {
        mvaddch(self.pos.y, self.pos.x, c as u32);
        self.pos.x += 1;
    }

    fn skiplines(&mut self, n: i32) {
        self.pos.y += n;
        self.pos.x = self.bounds.0.x;
    }

    fn set_pos(&mut self, new_side: ScreenSide, width: f64) {
        assert!(width > 0.0 && width <= 1.0);

        self.side = new_side;
        self.width = width;
    }
}

struct Item<'a> {
    icon: &'a str,
    chosen_icon: &'a str,
    chosen: bool,
    repr: String,
    preview: Option<String>,
}

impl<'a> Item<'a> {
    fn new(
        thing: &impl fmt::Display,
        icon: &'a str,
        chosen_icon: &'a str,
    ) -> Item<'a> {
        Item {
            icon,
            chosen_icon,
            chosen: false,
            repr: thing.to_string(),
            preview: None,
        }
    }

    fn select(&mut self) {
        self.chosen = !self.chosen;
    }

    fn chosen(&self) -> bool {
        self.chosen
    }

    fn icon(&self) -> &str {
        if self.chosen {
            self.chosen_icon
        } else {
            self.icon
        }
    }

    fn string(&self) -> &String {
        &self.repr
    }

    fn preview<D: fmt::Display>(&mut self, thing: D, func: &DispFunc<D>) {
        self.preview = Some(func.eval(thing));
    }
}

impl<'a> fmt::Display for Item<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", format!("{} {}", self.icon(), self.repr))
    }
}

struct Pair {
    y: i32,
    x: i32,
}

impl Pair {
    fn clone(&self) -> Pair {
        Pair {
            y: self.y,
            x: self.x,
        }
    }
}

impl fmt::Display for Pair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Pair({}, {})", self.y, self.x)
    }
}

/// Determines the side on which a pane should be located.
#[derive(Copy, Clone)]
pub enum ScreenSide {
    Left,
    Right,
    Top,
    Bottom,
    /// This option is not affected by width. It will always fill the screen.
    Full,
}

impl ScreenSide {
    fn get_bounds(
        &self,
        screen_bounds: (Pair, Pair),
        width: f64,
    ) -> (Pair, Pair) {
        assert!(width <= 1.0 && width > 0.0);
        match self {
            Self::Top => (
                screen_bounds.0,
                Pair {
                    y: ((screen_bounds.1.y as f64) * width) as i32,
                    x: screen_bounds.1.x,
                },
            ),
            Self::Bottom => (
                // TL: height * (1 - width) + 1
                // BR: BR
                Pair {
                    y: (((screen_bounds.1.y - screen_bounds.0.y) as f64)
                        * (1.0 - width)) as i32
                        + 1,
                    x: screen_bounds.0.x,
                },
                screen_bounds.1,
            ),
            Self::Left => (
                // TL: TL
                // BR: screen_width * width
                screen_bounds.0.clone(),
                Pair {
                    y: screen_bounds.1.y,
                    x: screen_bounds.0.x
                        + (((screen_bounds.1.x - screen_bounds.0.x) as f64)
                            * width) as i32,
                },
            ),
            Self::Right => (
                // TL: screen_width * (1 - width) + 1
                // BR: BR
                Pair {
                    y: screen_bounds.0.y,
                    x: screen_bounds.0.x
                        + (((screen_bounds.1.x - screen_bounds.0.x) as f64)
                            * (1.0 - width)) as i32
                        + 1,
                },
                screen_bounds.1.clone(),
            ),
            Self::Full => screen_bounds,
        }
    }
}

impl ops::Not for ScreenSide {
    type Output = Self;
    fn not(self) -> Self {
        match self {
            Self::Top => Self::Bottom,
            Self::Bottom => Self::Top,
            Self::Left => Self::Right,
            Self::Right => Self::Left,
            Self::Full => Self::Full,
        }
    }
}

struct DispFunc<D>
where
    D: fmt::Display,
{
    func: Box<dyn Fn(D) -> String>,
}

impl<D> DispFunc<D>
where
    D: fmt::Display,
{
    fn new(func: Box<dyn Fn(D) -> String>) -> DispFunc<D> {
        DispFunc { func }
    }
    fn eval(&self, param: D) -> String {
        (*self.func)(param)
    }
}

struct Preview<D>
where
    D: fmt::Display,
{
    func: DispFunc<D>,
    box_screen: Screen,
    screen: Screen,
    label: Option<String>,
}

impl<D> Preview<D>
where
    D: fmt::Display,
{
    fn new(func: DispFunc<D>, side: ScreenSide, width: f64) -> Preview<D> {
        let box_screen = Screen::new(side, width);
        let screen = Screen::new(side, width);

        Preview {
            func,
            box_screen,
            screen,
            label: None,
        }
    }

    fn draw_box(&mut self) {
        self.box_screen.draw_box(ScreenSide::Full, 1.0, &self.label);
    }

    fn show(&mut self) {
        self.box_screen.show();
        self.screen.show();
        self.update_bounds();
    }

    fn update_bounds(&mut self) {
        self.screen.bounds.0.y += 1;
        self.screen.bounds.0.x += 1;
        self.screen.bounds.1.y -= 1;
        self.screen.bounds.1.x -= 1;
    }

    fn refresh(&mut self) {
        self.screen.refresh();
        self.box_screen.refresh();
        self.update_bounds();
    }

    fn set_pos(&mut self, side: ScreenSide, width: f64) {
        self.screen.set_pos(side, width);
        self.box_screen.set_pos(side, width);
        self.update_bounds();
    }

    fn set_label(&mut self, label: String) {
        self.label = Some(label);
    }
}

// fn log(s: &str) -> std::io::Result<()> {
//     let mut file = OpenOptions::new()
//         .write(true)
//         .append(true)
//         .open("choose.log")
//         .unwrap();
//     writeln!(file, "{}", s)?;
//     Ok(())
// }

fn init_curses() {
    // Allow unicode characters
    let locale_conf = LcCategory::all;
    setlocale(locale_conf, "en_US.UTF-8");
    // Create curses screen
    initscr();
    // Use default color background
    use_default_colors();
    // Do not show typed characters on screen
    noecho();
    // Allow colors
    start_color();
    // Color used to highlight hovered selection
    init_pair(1, COLOR_BLACK, COLOR_WHITE);
    // -1 means default background
    init_pair(2, COLOR_RED, -1);
    init_pair(3, COLOR_GREEN, -1);

    // Hide cursor
    curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE);

    raw();
    keypad(stdscr(), true);
}

fn end_curses() {
    endwin();
}