-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
96 lines (83 loc) · 2.93 KB
/
main.rs
File metadata and controls
96 lines (83 loc) · 2.93 KB
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
use crossterm::{
cursor::{Hide, MoveTo, Show},
event::{poll, read, Event, KeyCode, KeyEvent, KeyModifiers},
execute,
style::{Print, ResetColor},
terminal::{
disable_raw_mode, enable_raw_mode, size, Clear, ClearType, EnterAlternateScreen,
LeaveAlternateScreen,
},
};
use std::{env, process, thread, time::Duration};
fn main() -> Result<(), std::io::Error> {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
println!("Usage: {} <duration in seconds>", args[0]);
process::exit(1);
}
let duration_secs = args[1]
.parse::<u64>()
.expect("Invalid duration, please provide a number");
let duration = Duration::from_secs(duration_secs);
enable_raw_mode()?;
execute!(std::io::stdout(), EnterAlternateScreen)?;
let start_time = std::time::Instant::now();
let end_time = start_time + duration;
loop {
let (width, height) = size()?;
let now = std::time::Instant::now();
let remaining_time = end_time - now;
if remaining_time <= Duration::from_secs(0) {
execute!(
std::io::stdout(),
Clear(ClearType::All),
MoveTo(width / 2, height / 2),
Hide,
Print("Time's up!"),
)?;
break;
}
let remaining_secs = remaining_time.as_secs();
let remaining_mins = remaining_secs / 60;
let remaining_secs = remaining_secs % 60;
let time_str = format!("{:02}:{:02}", remaining_mins, remaining_secs);
if poll(Duration::from_millis(500))? {
// It's guaranteed that the `read()` won't block when the `poll()`
// function returns `true`
match read()? {
// Event::FocusGained => println!("FocusGained"),
// Event::FocusLost => println!("FocusLost"),
Event::Key(event) => {
if handle_key_event(event) {
break;
}
}
_ => (),
// Event::Mouse(event) => println!("{:?}", event),
// Event::Paste(data) => println!("Pasted {:?}", data),
// Event::Resize(width, height) => println!("New size {}x{}", width, height),
}
}
execute!(
std::io::stdout(),
Clear(ClearType::All),
MoveTo(width / 2, height / 2),
Hide,
Print(time_str)
)?;
thread::sleep(Duration::from_millis(100));
}
execute!(std::io::stdout(), LeaveAlternateScreen, ResetColor)?;
execute!(std::io::stdout(), Show)?;
disable_raw_mode()?;
Ok(())
}
fn handle_key_event(event: KeyEvent) -> bool {
if event.code == KeyCode::Char('q') {
return true;
}
if event.code == KeyCode::Char('c') && event.modifiers == KeyModifiers::CONTROL {
return true;
}
return false;
}