git_iblame/extensions/
terminal_raw_mode_scope.rs

1use std::io;
2
3use crossterm::terminal;
4use log::warn;
5
6/// Enable or disable the
7/// [terminal raw mode](https://docs.rs/crossterm/latest/crossterm/terminal/index.html#raw-mode)
8/// while its instance is in scope.
9/// # Examples
10/// ```no_run
11/// # use git_iblame::TerminalRawModeScope;
12/// let _ = TerminalRawModeScope::new(true);
13/// ```
14pub struct TerminalRawModeScope {
15    is_enabled: bool,
16}
17
18impl TerminalRawModeScope {
19    pub fn new(enable: bool) -> io::Result<Self> {
20        Self::enable(enable)?;
21        Ok(Self { is_enabled: enable })
22    }
23
24    fn enable(enable: bool) -> io::Result<()> {
25        if enable {
26            terminal::enable_raw_mode()
27        } else {
28            terminal::disable_raw_mode()
29        }
30    }
31}
32
33impl Drop for TerminalRawModeScope {
34    fn drop(&mut self) {
35        if let Err(error) = Self::enable(!self.is_enabled) {
36            warn!("Failed to change terminal raw mode, ignored: {error}");
37        }
38    }
39}