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::extensions::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) -> io::Result<()> {
50 if !self.is_reset {
51 Self::enable(!self.is_enabled)?;
52 self.is_reset = true;
53 }
54 Ok(())
55 }
56
57 fn enable(enable: bool) -> io::Result<()> {
58 debug!("TerminalRawModeScope.enable({enable})");
59 if enable {
60 terminal::enable_raw_mode()
61 } else {
62 terminal::disable_raw_mode()
63 }
64 }
65}
66
67impl Drop for TerminalRawModeScope {
68 /// Calls `reset()` if it's not already reset.
69 /// This is called when the instance goes out of scope.
70 fn drop(&mut self) {
71 if let Err(error) = self.reset() {
72 warn!("Failed to change terminal raw mode, ignored: {error}");
73 }
74 }
75}