summaryrefslogtreecommitdiffstats
path: root/vendor/gix-prompt/src/unix.rs
blob: 91f664177e9889ae87a337f416e9c26df8161021 (plain)
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
/// The path to the default TTY on linux
pub const TTY_PATH: &str = "/dev/tty";

#[cfg(unix)]
pub(crate) mod imp {
    use std::{
        fs::File,
        io,
        io::{BufRead, Read, Write},
    };

    use parking_lot::{const_mutex, lock_api::MutexGuard, Mutex, RawMutex};
    use rustix::termios::{self, Termios};

    use crate::{unix::TTY_PATH, Error, Mode, Options};

    static TERM_STATE: Mutex<Option<Termios>> = const_mutex(None);

    /// Ask the user given a `prompt`, returning the result.
    pub(crate) fn ask(prompt: &str, Options { mode, .. }: &Options<'_>) -> Result<String, Error> {
        match mode {
            Mode::Disable => Err(Error::Disabled),
            Mode::Hidden => {
                let state = TERM_STATE.lock();
                let mut in_out = save_term_state_and_disable_echo(
                    state,
                    std::fs::OpenOptions::new().write(true).read(true).open(TTY_PATH)?,
                )?;
                in_out.write_all(prompt.as_bytes())?;

                let mut buf_read = std::io::BufReader::with_capacity(64, in_out);
                let mut out = String::with_capacity(64);
                buf_read.read_line(&mut out)?;

                out.pop();
                if out.ends_with('\r') {
                    out.pop();
                }
                buf_read.into_inner().restore_term_state()?;
                Ok(out)
            }
            Mode::Visible => {
                let mut in_out = std::fs::OpenOptions::new().write(true).read(true).open(TTY_PATH)?;
                in_out.write_all(prompt.as_bytes())?;

                let mut buf_read = std::io::BufReader::with_capacity(64, in_out);
                let mut out = String::with_capacity(64);
                buf_read.read_line(&mut out)?;
                Ok(out.trim_end().to_owned())
            }
        }
    }

    type TermiosGuard<'a> = MutexGuard<'a, RawMutex, Option<Termios>>;

    struct RestoreTerminalStateOnDrop<'a> {
        state: TermiosGuard<'a>,
        fd: File,
    }

    impl<'a> Read for RestoreTerminalStateOnDrop<'a> {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            self.fd.read(buf)
        }

        fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
            self.fd.read_vectored(bufs)
        }
    }

    impl<'a> Write for RestoreTerminalStateOnDrop<'a> {
        #[inline(always)]
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.fd.write(buf)
        }

        #[inline(always)]
        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
            self.fd.write_vectored(bufs)
        }

        #[inline(always)]
        fn flush(&mut self) -> io::Result<()> {
            self.fd.flush()
        }
    }

    impl<'a> RestoreTerminalStateOnDrop<'a> {
        fn restore_term_state(mut self) -> Result<(), Error> {
            let state = self.state.take().expect("BUG: we exist only if something is saved");
            termios::tcsetattr(&self.fd, termios::OptionalActions::Flush, &state)?;
            Ok(())
        }
    }

    impl<'a> Drop for RestoreTerminalStateOnDrop<'a> {
        fn drop(&mut self) {
            if let Some(state) = self.state.take() {
                termios::tcsetattr(&self.fd, termios::OptionalActions::Flush, &state).ok();
            }
        }
    }

    fn save_term_state_and_disable_echo(
        mut state: TermiosGuard<'_>,
        fd: File,
    ) -> Result<RestoreTerminalStateOnDrop<'_>, Error> {
        assert!(
            state.is_none(),
            "BUG: recursive calls are not possible and we restore afterwards"
        );

        let prev = termios::tcgetattr(&fd)?;
        let mut new = prev;
        *state = prev.into();

        new.c_lflag &= !termios::ECHO;
        new.c_lflag |= termios::ECHONL;
        termios::tcsetattr(&fd, termios::OptionalActions::Flush, &new)?;

        Ok(RestoreTerminalStateOnDrop { fd, state })
    }
}