aboutsummaryrefslogtreecommitdiff
path: root/src/ui.rs
blob: 4b27b82bb370ba54b493d67ca18456c22527351c (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
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::{
    error::Error,
    io,
    path::{Path, PathBuf},
    thread::sleep,
    time::{Duration, Instant},
};
use tui::{
    backend::{Backend, CrosstermBackend},
    layout::{Alignment, Constraint, Corner, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Span, Spans},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
    Frame, Terminal,
};

use crate::generation::*;


pub struct StatefulList<T> {
    state: ListState,
    items: Vec<T>,
}

impl<T> StatefulList<T> {
    fn with_items(items: Vec<T>) -> StatefulList<T> {
        StatefulList {
            state: ListState::default(),
            items,
        }
    }

    fn next(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i >= self.items.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.state.select(Some(i));
    }

    fn previous(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i == 0 {
                    self.items.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.state.select(Some(i));
    }

    fn unselect(&mut self) {
        self.state.select(None);
    }
}

/// This struct holds the current state of the app. In particular, it has the `items` field which is a wrapper
/// around `ListState`. Keeping track of the items state let us render the associated widget with its state
/// and have access to features such as natural scrolling.
///
/// Check the event handling at the bottom to see how to change the state on incoming events.
/// Check the drawing logic for items on how to specify the highlighting style for selected items.
pub struct App {
    pub items: StatefulList<(String, PathBuf)>,
    pub flag_cur: bool,
    pub layout: Layout,
    pub cur_gen: Gen,
}

impl App {
    pub fn new() -> App {
        let mut v = vec![];
        for i in 1..=513 {
            let name = format!("pattern{}", i);
            let p = format!("./presets/patterns/pattern{}.txt", i);
            v.push((name.to_owned(), Path::new(p.as_str()).to_owned()));
        }
        App {
            items: StatefulList::with_items(v),
            flag_cur: false,
            layout: Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Percentage(15), Constraint::Percentage(85)].as_ref()),
            cur_gen: Gen::new(),
        }
    }
}

pub fn run_app<B: Backend>(
    terminal: &mut Terminal<B>,
    mut app: App,
) -> io::Result<()> {
    let mut last_tick = Instant::now();
    let mut item_cnt = 1;
    loop {
        terminal.draw(|f| ui_list(f, &mut app))?;
        let timeout = Duration::from_millis(32);
        if crossterm::event::poll(timeout)? {
            if let Event::Key(key) = event::read()? {
                match key.code {
                    KeyCode::Char('q') => return Ok(()),
                    KeyCode::Left | KeyCode::Char('h') => app.items.unselect(),
                    KeyCode::Down | KeyCode::Char('j') => {
                        if item_cnt >= app.items.items.len() - 1 {
                            item_cnt = 0;
                        } else {
                            item_cnt += 1;
                        }
                        app.items.next();
                        app.cur_gen =
                            gen_from_file(&app.items.items[item_cnt].1);
                    }
                    KeyCode::Up | KeyCode::Char('k') => {
                        if item_cnt == 0 {
                            item_cnt = app.items.items.len() - 1;
                        }
                        else {
                            item_cnt -= 1;
                        }
                        app.items.previous();
                        app.cur_gen =
                            gen_from_file(&app.items.items[item_cnt].1);
                    }
                    KeyCode::Char('n') => {
                        terminal.draw(|f| ui_game(f, &mut app))?;
                    }
                    KeyCode::Char('a') => 'animate: loop {
                        terminal.draw(|f| ui_game(f, &mut app))?;
                        sleep(Duration::from_millis(32));
                        if (crossterm::event::poll(Duration::from_millis(1))).unwrap() {
                            if let Event::Key(k) = event::read().unwrap() {
                                match k.code {
                                    KeyCode::Char('s') => break 'animate,
                                    _ => {}
                                }
                            }
                        }
                    },
                    _ => {}
                }
            }
        }
    }
}

fn ui_list<B: Backend>(f: &mut Frame<B>, app: &mut App) {
    let chunks = app.layout.split(f.size());

    let items: Vec<ListItem> = app
        .items
        .items
        .iter()
        .map(|i| {
            let lines = vec![Spans::from(i.0.as_str())];
            ListItem::new(lines).style(Style::default().fg(Color::Red).bg(Color::Black))
        })
        .collect();

    let items = List::new(items)
        .block(Block::default().borders(Borders::ALL).title("Cool Paterns"))
        .highlight_style(
            Style::default()
                .bg(Color::White)
                .add_modifier(Modifier::ITALIC),
        )
        .highlight_symbol("-> ");

    f.render_stateful_widget(items, chunks[0], &mut app.items.state);

    if !app.flag_cur {
        app.cur_gen = new_gen(&chunks[1], app);
    }
    let spans = gen_to_spans(&app.cur_gen);
    render_gen(f, chunks[1], &spans);
}

fn ui_game<B: Backend>(f: &mut Frame<B>, app: &mut App) {
    let chunks = app.layout.split(f.size());

    let items: Vec<ListItem> = app
        .items
        .items
        .iter()
        .map(|i| {
            let lines = vec![Spans::from(i.0.as_str())];
            ListItem::new(lines).style(Style::default().fg(Color::Red).bg(Color::Black))
        })
        .collect();

    // Create a List from all list items and highlight the currently selected one
    let items = List::new(items)
        .block(Block::default().borders(Borders::ALL).title("Cool Patterns"))
        .highlight_style(
            Style::default()
                .bg(Color::Blue)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("> ");

    f.render_stateful_widget(items, chunks[0], &mut app.items.state);


    let nxt = next_gen(app);
    let spans = gen_to_spans(&nxt);
    render_gen(f, chunks[1], &spans)
}