File: app.rs

package info (click to toggle)
rust-cotp 1.9.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,392 kB
  • sloc: python: 168; xml: 14; sh: 9; makefile: 4
file content (306 lines) | stat: -rw-r--r-- 11,007 bytes parent folder | download | duplicates (2)
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
use std::error;

use crate::interface::enums::Focus;
use crate::interface::enums::Page;
use crate::interface::enums::Page::{Main, Qrcode};
use crate::otp::otp_element::OTPDatabase;
use ratatui::layout::Rect;
use ratatui::layout::{Alignment, Constraint, Direction, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, Borders, Cell, Clear, Gauge, Paragraph, Row, Table, Wrap};
use ratatui::Frame;

use crate::interface::stateful_table::{fill_table, StatefulTable};
use crate::utils::percentage;

use super::enums::PopupAction;
use super::popup::centered_rect;

const LARGE_APPLICATION_WIDTH: u16 = 75;

/// Application result type.
pub type AppResult<T> = Result<T, Box<dyn error::Error>>;

const DEFAULT_QRCODE_LABEL: &str = "Press enter to copy the OTP URI code";

/// Application.
pub struct App<'a> {
    /// Is the application running?
    pub running: bool,
    title: String,
    pub(crate) table: StatefulTable,
    pub(crate) database: &'a mut OTPDatabase,
    progress: u16,
    /// Text to print replacing the percentage
    pub(crate) label_text: String,
    pub(crate) print_percentage: bool,
    pub(crate) current_page: Page,
    pub(crate) search_query: String,
    pub(crate) focus: Focus,
    pub(crate) popup: Popup,

    /// Info text in the `QRCode` page
    pub(crate) qr_code_page_label: &'static str,
}

pub struct Popup {
    pub(crate) text: String,
    pub(crate) action: PopupAction,
    pub(crate) percent_x: u16,
    pub(crate) percent_y: u16,
}

impl<'a> App<'a> {
    /// Constructs a new instance of [`App`].
    pub fn new(database: &'a mut OTPDatabase) -> Self {
        let mut title = String::from(env!("CARGO_PKG_NAME"));
        title.push_str(" v");
        // Settings cotp version from env var defined in build.rs
        title.push_str(env!("COTP_VERSION"));
        Self {
            running: true,
            title,
            table: StatefulTable::new(database.elements_ref()),
            database,
            progress: percentage(),
            label_text: String::new(),
            print_percentage: true,
            current_page: Page::default(),
            search_query: String::new(),
            focus: Focus::MainPage,
            popup: Popup {
                text: String::new(),
                action: PopupAction::EditOtp,
                percent_x: 60,
                percent_y: 20,
            },
            qr_code_page_label: DEFAULT_QRCODE_LABEL,
        }
    }

    pub(crate) fn reset(&mut self) {
        self.current_page = Page::default();
        self.print_percentage = true;
        self.qr_code_page_label = DEFAULT_QRCODE_LABEL;
    }

    /// Handles the tick event of the terminal.
    pub fn tick(&mut self, force_update: bool) {
        // Update progress bar
        let new_progress = percentage();
        // Check for new cycle
        if force_update || new_progress < self.progress {
            // Update codes
            self.table.items.clear();
            fill_table(&mut self.table, self.database.elements_ref());
        }
        self.progress = new_progress;
    }

    /// Renders the user interface widgets.
    pub fn render(&mut self, frame: &mut Frame<'_>) {
        match &self.current_page {
            Main => self.render_main_page(frame),
            Qrcode => self.render_qrcode_page(frame),
        }
    }

    fn render_qrcode_page(&self, frame: &mut Frame<'_>) {
        let paragraph = self
            .table
            .state
            .selected()
            .and_then(|index| self.database.elements_ref().get(index))
            .map_or_else(
                || {
                    Paragraph::new("No element is selected")
                        .block(Block::default().title("Nope").borders(Borders::ALL))
                        .style(Style::default().fg(Color::White).bg(Color::Reset))
                        .alignment(Alignment::Center)
                        .wrap(Wrap { trim: true })
                },
                |element| {
                    let title = if element.label.is_empty() {
                        element.issuer.clone()
                    } else {
                        format!("{} - {}", &element.issuer, &element.label)
                    };
                    Paragraph::new(format!(
                        "{}\n{}",
                        element.get_qrcode(),
                        self.qr_code_page_label
                    ))
                    .block(Block::default().title(title).borders(Borders::ALL))
                    .style(Style::default().fg(Color::White).bg(Color::Reset))
                    .alignment(Alignment::Center)
                    .wrap(Wrap { trim: true })
                },
            );
        Self::render_paragraph(frame, paragraph);
    }

    fn render_paragraph(frame: &mut Frame<'_>, paragraph: Paragraph) {
        let rects = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(100)].as_ref())
            .split(frame.area());

        frame.render_widget(paragraph, rects[0]);
    }

    fn render_main_page(&mut self, frame: &mut Frame<'_>) {
        let height = frame.area().height;
        let rects = Layout::default()
            .direction(Direction::Vertical)
            .constraints(
                [
                    Constraint::Length(3),          // Search bar
                    Constraint::Length(height - 8), // Table + Info Box
                    Constraint::Length(1),          // Progress bar
                ]
                .as_ref(),
            )
            .margin(2)
            .split(frame.area());

        let search_bar_title = "Press CTRL + F to search a code...";
        let search_bar = Paragraph::new(&*self.search_query)
            .block(
                Block::default()
                    .title(search_bar_title)
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(if self.focus == Focus::SearchBar {
                        Color::LightRed
                    } else {
                        Color::White
                    })),
            )
            .style(Style::default().fg(Color::White).bg(Color::Reset))
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true });

        let progress_label = if self.print_percentage {
            format!("{}%", self.progress)
        } else {
            self.label_text.clone()
        };
        let progress_bar = Gauge::default()
            .block(Block::default())
            .gauge_style(
                Style::default()
                    .bg(Color::White)
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::BOLD),
            )
            .percent(self.progress)
            .label(progress_label);

        frame.render_widget(search_bar, rects[0]);
        self.render_table_box(frame, rects[1]);
        frame.render_widget(progress_bar, rects[2]);
        if self.focus == Focus::Popup {
            self.render_alert(frame);
        }
    }

    fn render_alert(&mut self, frame: &mut Frame<'_>) {
        let block = Block::default().title("Alert").borders(Borders::ALL);
        let paragraph = Paragraph::new(&*self.popup.text)
            .block(block)
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true });
        let area = centered_rect(self.popup.percent_x, self.popup.percent_y, frame.area());
        frame.render_widget(Clear, area);
        //this clears out the background
        frame.render_widget(paragraph, area);
    }

    fn render_table_box(&mut self, frame: &mut Frame<'_>, area: Rect) {
        let constraints = if Self::is_large_application(frame) {
            vec![Constraint::Percentage(80), Constraint::Percentage(20)]
        } else {
            vec![Constraint::Percentage(100)]
        };
        let chunks = Layout::default()
            .constraints(constraints)
            .direction(Direction::Horizontal)
            .split(area);

        let header_cells = ["Id", "Issuer", "Label", "OTP"]
            .iter()
            .map(|h| Cell::from(*h).style(Style::default().fg(Color::Black)));
        let header = Row::new(header_cells)
            .style(
                Style::default()
                    .bg(Color::White)
                    .add_modifier(Modifier::BOLD),
            )
            .height(1)
            .bottom_margin(1);
        let rows = self.table.items.iter().map(|item| {
            Row::new(item.cells())
                .height(item.height())
                .bottom_margin(1)
        });

        const TABLE_WIDTHS: &[Constraint] = &[
            Constraint::Percentage(5),
            Constraint::Percentage(35),
            Constraint::Percentage(35),
            Constraint::Percentage(25),
        ];

        let t = Table::new(rows, TABLE_WIDTHS)
            .header(header)
            .block(
                Block::default()
                    .borders(Borders::TOP | Borders::BOTTOM)
                    .title(self.title.as_str()),
            )
            .highlight_style(
                Style::default()
                    .bg(Color::White)
                    .fg(Color::Black)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol("-> ");

        let selected_element = match self.table.state.selected() {
            Some(index) => self.database.get_element(index),
            None => None,
        };
        let mut text = if let Some(element) = selected_element {
            format!(
                "
            Type: {}
            Algorithm: {}
            Counter: {}
            Pin: {}
            ",
                element.type_,
                element.algorithm,
                element
                    .counter
                    .map_or_else(|| String::from("N/A"), |e| e.to_string()),
                element.pin.clone().unwrap_or_else(|| String::from("N/A"))
            )
        } else {
            String::new()
        };

        text.push_str("\n\n         Press '?' to get help\n");
        let paragraph = Paragraph::new(text)
            .block(Block::default().title("Code info").borders(Borders::ALL))
            .style(Style::default().fg(Color::White).bg(Color::Reset))
            .alignment(Alignment::Left)
            .wrap(Wrap { trim: true });
        frame.render_stateful_widget(t, chunks[0], &mut self.table.state);
        if Self::is_large_application(frame) {
            frame.render_widget(paragraph, chunks[1]);
        }
    }

    fn is_large_application(frame: &mut Frame<'_>) -> bool {
        frame.area().width >= LARGE_APPLICATION_WIDTH
    }
}