git_iblame/extensions/
terminal_raw_mode_scope.rs

1use std::io;
2
3use crossterm::terminal;
4use log::*;
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///
10/// While it automatically resets the mode when it's out of scope,
11/// `reset()` should be called explicitly when the mode should be reset
12/// or at the end of the scope
13/// to avoid it being dropped earlier by the compiler.
14/// # Examples
15/// ```no_run
16/// # fn main() -> std::io::Result<()> {
17/// use git_iblame::TerminalRawModeScope;
18///
19/// let mut terminal_raw_mode = TerminalRawModeScope::new(true)?;
20/// // Do the work.
21/// // If it returns early, the terminal raw mode will be reset automatically.
22/// terminal_raw_mode.reset();
23/// # Ok(())
24/// # }
25/// ```
26pub struct TerminalRawModeScope {
27    is_enabled: bool,
28    is_reset: bool,
29}
30
31impl TerminalRawModeScope {
32    /// Enable the raw mode if `enable` is true,
33    /// or disable it if `enable` is false.
34    pub fn new(enable: bool) -> io::Result<Self> {
35        Self::enable(enable)?;
36        Ok(Self {
37            is_enabled: enable,
38            is_reset: false,
39        })
40    }
41
42    /// Reset the terminal raw mode.
43    /// This should be called when the mode should be reset,
44    /// or at the end of the scope.
45    ///
46    /// Even if the mode should be reset at the end of the scope,
47    /// and that the `Drop` trait should reset the raw mode,
48    /// it should be called to avoid it being dropped earlier by the compiler.
49    pub fn reset(&mut self) {
50        if !self.is_reset {
51            if let Err(error) = Self::enable(!self.is_enabled) {
52                warn!("Failed to change terminal raw mode, ignored: {error}");
53            }
54            self.is_reset = true;
55        }
56    }
57
58    fn enable(enable: bool) -> io::Result<()> {
59        debug!("TerminalRawModeScope.enable({enable})");
60        if enable {
61            terminal::enable_raw_mode()
62        } else {
63            terminal::disable_raw_mode()
64        }
65    }
66}
67
68impl Drop for TerminalRawModeScope {
69    /// Calls `reset()` if it's not already reset.
70    /// This is called when the instance goes out of scope.
71    fn drop(&mut self) {
72        self.reset();
73    }
74}