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
pub mod event;
mod sys;
pub mod util;
use crate::util::{Point, Size};
use std::io::{self, Write};
#[derive(Debug)]
pub struct Terminal<'a> {
pub stdout: io::BufWriter<io::StdoutLock<'a>>,
pub size: Size,
#[cfg(debug_assertions)]
pub flush_count: usize,
initialized: bool,
with_mouse: bool,
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct NotTTY;
impl<'a> Terminal<'a> {
pub fn new(stdout: io::StdoutLock<'a>) -> Result<Self, NotTTY> {
if !Self::is_tty(&stdout) {
return Err(NotTTY);
}
let writer = io::BufWriter::new(stdout);
Ok(Self {
stdout: writer,
size: Self::size(),
#[cfg(debug_assertions)]
flush_count: 0,
initialized: false,
with_mouse: false
})
}
pub fn write(&mut self, string: &str) {
self.stdout.write_all(string.as_bytes()).unwrap();
}
pub fn write_bytes(&mut self, bytes: &[u8]) {
self.stdout.write_all(bytes).unwrap();
}
pub fn flush(&mut self) {
self.stdout.flush().unwrap();
#[cfg(debug_assertions)]
{
if self.initialized {
self.flush_count += 1;
self.save_cursor_point();
self.set_cursor(Point { x: 0, y: 0 });
let flush_count = self.flush_count;
self.write(&format!("Flush count: {}", flush_count));
self.restore_cursor_point();
}
}
}
fn set_panic_hook(with_mouse: bool) {
use std::panic;
let current_panic_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic_info| {
let stdout = io::stdout();
let mut terminal = Terminal::new(stdout.lock()).unwrap();
terminal.initialized = true;
terminal.with_mouse = with_mouse;
terminal.deinitialize();
terminal.flush();
current_panic_hook(panic_info);
}));
}
pub fn initialize(&mut self, title: Option<&str>, with_mouse: bool) {
self.enter_alternate_dimension();
self.enable_raw_mode();
self.hide_cursor();
if let Some(title) = title {
self.set_title(title);
}
if with_mouse {
self.enable_mouse_capture();
}
Self::set_panic_hook(with_mouse);
self.initialized = true;
}
pub fn deinitialize(&mut self) {
if !self.initialized {
panic!("terminal is not initialized");
}
self.exit_alternate_dimension();
self.disable_raw_mode();
self.show_cursor();
if self.with_mouse {
self.disable_mouse_capture();
}
self.initialized = false;
}
pub fn contains(&self, point: Point) -> bool {
point.x > 0 && point.x < self.size.width && point.y < self.size.height && point.y > 0
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}