clock_cli/
tui.rs

1// Copyright (C) 2020 Tianyi Shi
2//
3// This file is part of clock-cli-rs.
4//
5// clock-cli-rs is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// clock-cli-rs is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with clock-cli-rs.  If not, see <http://www.gnu.org/licenses/>.
17
18mod stopwatch;
19mod timer;
20use crate::{notify::notify, utils::PrettyDuration};
21use clock_core::{stopwatch::StopwatchData, timer::TimerData};
22use cursive::{traits::*, views::Dialog, Cursive};
23pub use stopwatch::StopwatchView;
24pub use timer::TimerView;
25
26pub fn stopwatch() {
27    let mut siv = cursive::default();
28    let stopwatch = StopwatchView::new();
29    siv.add_layer(
30        stopwatch
31            .with_laps(8)
32            .on_stop(|s: &mut Cursive, stopwatch| s.add_layer(Dialog::info(summarize(&stopwatch))))
33            .with_name("stopwatch"),
34    );
35    siv.set_fps(15);
36    siv.run();
37}
38
39fn summarize(stopwatch: &StopwatchData) -> String {
40    let elapsed = stopwatch.elapsed;
41    let average = stopwatch.elapsed / stopwatch.laps.len() as i32;
42    let max = stopwatch.laps.iter().max().unwrap();
43    let min = stopwatch.laps.iter().min().unwrap();
44    format!(
45        "Elapsed time: {}\nAverage: {}\nMax: {}\nMin: {}",
46        elapsed.pretty(),
47        average.pretty(),
48        max.pretty(),
49        min.pretty()
50    )
51}
52
53fn timer_on_finish(data: TimerData) {
54    let expected_duration = data.duration_expected().pretty_s();
55    let actual_duration = data.duration_actual().pretty_s();
56    let msg = &format!(
57        "Expected: {}\nActual: {}",
58        &expected_duration, &actual_duration,
59    );
60
61    notify(msg).unwrap();
62
63    match notify(msg) {
64        Ok(_) => {}
65        Err(_) => {}
66    }
67}
68
69#[allow(dead_code)]
70fn timer_on_finish_debug(s: &mut Cursive, data: TimerData) {
71    s.add_layer(Dialog::info(format!("{:?}", data)));
72}
73
74pub fn timer(h: u8, m: u8, s: u8) {
75    let mut siv = cursive::default();
76    let timer = TimerView::new(h, m, s);
77    siv.add_layer(timer.on_finish(|_: &mut Cursive, timer| timer_on_finish(timer)));
78    //siv.set_fps(15);
79    siv.set_autorefresh(true);
80    siv.run();
81}