console_display/display/
display_driver.rs

1use std::{
2    io::{
3        self,
4        Write,
5    },
6    ops::{
7        Deref,
8        DerefMut,
9    },
10    thread,
11    time::{
12        Duration,
13        Instant,
14    },
15};
16
17use crossterm::{
18    cursor,
19    event::{
20        self,
21        Event,
22        KeyCode,
23        KeyEvent,
24        KeyModifiers,
25    },
26    terminal,
27};
28
29use crate::widget::{
30    DynamicWidget,
31    single_widget::PaddingWidget,
32};
33
34pub enum UpdateStatus {
35    Break,
36    Continue,
37}
38
39type UpdateFunction<T> =
40    dyn FnMut(&mut DisplayDriver<T>, Option<KeyEvent>) -> UpdateStatus;
41
42/// Represents a display driver responsible for handling the interaction between the displays and the terminal.
43pub struct DisplayDriver<T: DynamicWidget> {
44    original_width: u16,
45    original_height: u16,
46    display: PaddingWidget<T>,
47    on_update: Option<Box<UpdateFunction<T>>>,
48    target_frame_time: Duration,
49}
50
51impl<T: DynamicWidget> DisplayDriver<T> {
52    /// Convenience method to build a blank display struct with specified dimensions
53    pub fn new(widget: T) -> Self {
54        let (original_width, original_height) =
55            match crossterm::terminal::size() {
56                Ok((w, h)) => (w, h),
57                Err(_) => (0, 0),
58            };
59
60        Self {
61            original_width,
62            original_height,
63            display: PaddingWidget::new(widget, 0, 0, 0, 0),
64            target_frame_time: Duration::ZERO,
65            on_update: None,
66        }
67    }
68
69    /// Prints the display to the terminal.
70    ///
71    /// # Errors
72    ///
73    /// May return an error if write! is unsuccessful.
74    pub fn print_display(&self) -> Result<(), io::Error> {
75        let mut stdout = io::stdout();
76
77        write!(stdout, "\x1B[H")?;
78        write!(stdout, "{}", self.display.string_data())?;
79
80        Ok(())
81    }
82
83    /// Initializes the display driver.
84    /// This function enables terminal raw mode and
85    /// sets the dimensions of the screen to match the widget's dimensions.
86    /// It enters alternate screen mode,
87    /// hides the cursor and disables line wrapping.
88    ///
89    /// # Errors
90    ///
91    /// Returns an error when any on the actions above fail.
92    /// Note that resizing the terminal does not fail, if the terminal does not support it.
93    pub fn initialize(&mut self) -> Result<(), io::Error> {
94        let mut stdout = io::stdout();
95
96        // enables terminal raw mode
97        terminal::enable_raw_mode()?;
98
99        crossterm::execute!(
100            stdout,
101            terminal::EnterAlternateScreen, // use alternate screen
102            terminal::SetSize(
103                self.child()
104                    .width_characters()
105                    .try_into()
106                    .unwrap_or(u16::MAX),
107                self.child()
108                    .height_characters()
109                    .try_into()
110                    .unwrap_or(u16::MAX)
111            ), // set dimensions of screen
112            terminal::DisableLineWrap,      // disable line wrapping
113            terminal::Clear(terminal::ClearType::All), // clear screen
114            cursor::Hide,                   // hide cursor blinking
115        )?;
116
117        Ok(())
118    }
119
120    const fn original_width(&self) -> &u16 {
121        &self.original_width
122    }
123
124    const fn orignal_height(&self) -> &u16 {
125        &self.original_height
126    }
127
128    const fn child(&self) -> &T {
129        &self.display
130    }
131
132    const fn child_mut(&mut self) -> &mut T {
133        &mut self.display
134    }
135
136    pub fn set_on_update<F>(&mut self, on_update: F)
137    where
138        F: FnMut(&mut Self, Option<KeyEvent>) -> UpdateStatus + 'static,
139    {
140        self.on_update = Some(Box::new(on_update));
141    }
142
143    pub const fn set_target_frame_time(&mut self, frame_time: Duration) {
144        self.target_frame_time = frame_time;
145    }
146
147    pub fn set_target_frame_rate(&mut self, frame_rate: f32) {
148        self.target_frame_time = Duration::from_secs_f32(1. / frame_rate);
149    }
150
151    /// This function encapsulates the update loop of the display.
152    /// As such it may or may not return depending on the update callback set with
153    /// `set_on_update`.
154    /// This function prints the display.
155    /// Queries user input and exits on Ctrl-C.
156    /// Forwards keystrokes to the provided callback and invokes it.
157    /// Sleeps so the target frame rate is not exceeded.
158    ///
159    /// # Panics
160    ///
161    /// This function panics when the display could not be printed.
162    pub fn update(&mut self) {
163        loop {
164            let start = Instant::now();
165
166            let (width, height) = match crossterm::terminal::size() {
167                Ok((w, h)) => (w, h),
168                Err(_) => (0, 0),
169            };
170
171            let padding_vertical =
172                (height as usize).saturating_sub(self.height_characters());
173            let padding_horizontal =
174                (width as usize).saturating_sub(self.width_characters());
175
176            self.display.set_padding_left(padding_horizontal / 2);
177            self.display.set_padding_top(padding_vertical / 2);
178            self.display.set_padding_right(padding_horizontal / 2);
179            self.display.set_padding_bottom(padding_vertical / 2);
180
181            self.print_display().expect("Could not print display.");
182
183            let mut latest_event = None;
184            while event::poll(Duration::from_millis(0)).unwrap() {
185                if let Event::Key(key_event) = event::read().unwrap() {
186                    latest_event = Some(key_event);
187                }
188            }
189
190            if let Some(key_event) = latest_event &&
191                key_event.code == KeyCode::Char('c') &&
192                key_event.modifiers.contains(KeyModifiers::CONTROL)
193            {
194                break; // Exit on Ctrl-C
195            }
196
197            let mut update_status = UpdateStatus::Continue;
198            if let Some(mut callback) = self.on_update.take() {
199                update_status = callback(self, latest_event);
200                self.on_update = Some(callback);
201            }
202            match update_status {
203                UpdateStatus::Break => break,
204                UpdateStatus::Continue => {}
205            }
206
207            thread::sleep(
208                self.target_frame_time.saturating_sub(start.elapsed()),
209            );
210        }
211    }
212}
213
214impl<T: DynamicWidget> const Deref for DisplayDriver<T> {
215    type Target = T;
216
217    fn deref(&self) -> &Self::Target {
218        self.child()
219    }
220}
221
222impl<T: DynamicWidget> const DerefMut for DisplayDriver<T> {
223    fn deref_mut(&mut self) -> &mut Self::Target {
224        self.child_mut()
225    }
226}
227
228impl<T: DynamicWidget> Drop for DisplayDriver<T> {
229    fn drop(&mut self) {
230        let mut stdout = io::stdout();
231
232        let _ = crossterm::execute!(
233            stdout,
234            terminal::EnableLineWrap, // disable line wrapping
235            terminal::LeaveAlternateScreen, // return to previous screen
236            cursor::Show,             // show cursor blinking
237        );
238
239        // reset dimensions of screen
240        if *self.original_width() != 0 && *self.orignal_height() != 0 {
241            let _ = crossterm::execute!(
242                stdout,
243                terminal::SetSize(
244                    *self.original_width(),
245                    *self.orignal_height()
246                )
247            );
248        }
249
250        // disable terminal raw mode
251        let _ = terminal::disable_raw_mode();
252    }
253}