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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! The entry point module for presenting data to the terminal.
//!
//! To get started, create a terminal, create a root window from it, use it to render stuff to the
//! terminal and finally present the terminal content to the physical terminal.
//!
//! # Examples:
//!
//! ```no_run //tests do not provide a fully functional terminal
//! use unsegen::base::Terminal;
//! use std::io::stdout;
//! let stdout = stdout();
//! let mut term = Terminal::new(stdout.lock()).unwrap();
//!
//! let mut done = false;
//! while !done {
//!     // Process data, update data structures
//!     done = true; // or whatever condition you like
//!
//!     {
//!         let win = term.create_root_window();
//!         // use win to draw something
//!     }
//!     term.present();
//!
//! }
//! ```
use base::{Height, Style, Width, Window, WindowBuffer};
use ndarray::Axis;
use raw_tty::TtyWithGuard;
use std::io;
use std::io::{StdoutLock, Write};
use std::os::unix::io::AsRawFd;
use termion;

use nix::sys::signal::{killpg, pthread_sigmask, SigSet, SigmaskHow, SIGCONT, SIGTSTP};
use nix::unistd::getpgrp;

/// A type providing an interface to the underlying physical terminal.
/// This also provides the entry point for any rendering to the terminal buffer.
pub struct Terminal<'a, T = StdoutLock<'a>>
where
    T: AsRawFd + Write,
{
    values: WindowBuffer,
    terminal: TtyWithGuard<T>,
    size_has_changed_since_last_present: bool,
    _phantom: ::std::marker::PhantomData<&'a ()>,
}

impl<'a, T: Write + AsRawFd> Terminal<'a, T> {
    /// Create a new terminal. The terminal takes control of the provided io sink (usually stdout)
    /// and performs all output on it.
    ///
    /// If the terminal cannot be created (e.g., because the provided io sink does not allow for
    /// setting up raw mode), the error is returned.
    pub fn new(sink: T) -> io::Result<Self> {
        let mut terminal = TtyWithGuard::new(sink)?;
        terminal.set_raw_mode()?;
        let mut term = Terminal {
            values: WindowBuffer::new(Width::new(0).unwrap(), Height::new(0).unwrap()),
            terminal,
            size_has_changed_since_last_present: true,
            _phantom: Default::default(),
        };
        term.enter_tui()?;
        Ok(term)
    }

    /// This method is intended to be called when the process received a SIGTSTP.
    ///
    /// The terminal state is restored, and the process is actually stopped within this function.
    /// When the process then receives a SIGCONT it sets up the terminal state as expected again
    /// and returns from the function.
    ///
    /// The usual way to deal with SIGTSTP (and signals in general) is to block them and `waidpid`
    /// for them in a separate thread which sends the events into some fifo. The fifo can be polled
    /// in an event loop. Then, if in the main event loop a SIGTSTP turns up, *this* function
    /// should be called.
    pub fn handle_sigtstp(&mut self) -> io::Result<()> {
        self.leave_tui()?;

        let mut stop_and_cont = SigSet::empty();
        stop_and_cont.add(SIGCONT);
        stop_and_cont.add(SIGTSTP);

        // 1. Unblock SIGTSTP and SIGCONT, so that we actually stop when we receive another SIGTSTP
        pthread_sigmask(SigmaskHow::SIG_UNBLOCK, Some(&stop_and_cont), None)
            .map_err(|e| e.as_errno().expect("Only expecting io errors"))?;

        // 2. Reissue SIGTSTP (this time to whole the process group!)...
        killpg(getpgrp(), SIGTSTP).map_err(|e| e.as_errno().expect("Only expecting io errors"))?;
        // ... and stop!
        // Now we are waiting for a SIGCONT.

        // 3. Once we receive a SIGCONT we block SIGTSTP and SIGCONT again and resume.
        pthread_sigmask(SigmaskHow::SIG_BLOCK, Some(&stop_and_cont), None)
            .map_err(|e| e.as_errno().expect("Only expecting io errors"))?;

        self.enter_tui()
    }

    /// Set up the terminal for "full screen" work (i.e., hide cursor, switch to alternate screen).
    fn enter_tui(&mut self) -> io::Result<()> {
        write!(
            self.terminal,
            "{}{}",
            termion::screen::ToAlternateScreen,
            termion::cursor::Hide
        )?;
        self.terminal.set_raw_mode()?;
        self.terminal.flush()?;
        Ok(())
    }

    /// Restore terminal from "full screen" (i.e., show cursor again, switch to main screen).
    fn leave_tui(&mut self) -> io::Result<()> {
        write!(
            self.terminal,
            "{}{}",
            termion::screen::ToMainScreen,
            termion::cursor::Show
        )?;
        self.terminal.modify_mode(|m| m)?; //Restore saved mode
        self.terminal.flush()?;
        Ok(())
    }

    /// Temporarily switch back to main terminal screen, restore terminal state, then execute `f`
    /// and subsequently switch back to tui mode again.
    ///
    /// In other words: Execute a function `f` in "normal" terminal mode. This can be useful if the
    /// application executes a subprocess that is expected to take control of the tty temporarily.
    pub fn on_main_screen<R, F: FnOnce() -> R>(&mut self, f: F) -> io::Result<R> {
        self.leave_tui()?;
        let res = f();
        self.enter_tui()?;
        Ok(res)
    }

    /// Create a root window that covers the whole terminal grid.
    ///
    /// Use the buffer to manipulate the current window buffer and use present subsequently to
    /// write out the buffer to the actual terminal.
    pub fn create_root_window(&mut self) -> Window {
        let (x, y) = termion::terminal_size().expect("get terminal size");
        let x = Width::new(x as i32).unwrap();
        let y = Height::new(y as i32).unwrap();
        if x != self.values.as_window().get_width() || y != self.values.as_window().get_height() {
            self.size_has_changed_since_last_present = true;
            self.values = WindowBuffer::new(x, y);
        } else {
            self.values.as_window().clear();
        }

        self.values.as_window()
    }

    /// Present the current buffer content to the actual terminal.
    pub fn present(&mut self) {
        let mut current_style = Style::default();

        if self.size_has_changed_since_last_present {
            write!(self.terminal, "{}", termion::clear::All).expect("clear");
            self.size_has_changed_since_last_present = false;
        }
        for (y, line) in self.values.storage().axis_iter(Axis(0)).enumerate() {
            write!(
                self.terminal,
                "{}",
                termion::cursor::Goto(1, (y + 1) as u16)
            )
            .expect("move cursor");
            let mut buffer = String::with_capacity(line.len());
            for c in line.iter() {
                if c.style != current_style {
                    current_style.set_terminal_attributes(&mut self.terminal);
                    write!(self.terminal, "{}", buffer).expect("write buffer");
                    buffer.clear();
                    current_style = c.style;
                }
                let grapheme_cluster = match c.grapheme_cluster.as_str() {
                    c @ "\t" | c @ "\n" | c @ "\r" | c @ "\0" => {
                        panic!("Invalid grapheme cluster written to terminal: {:?}", c)
                    }
                    x => x,
                };
                buffer.push_str(grapheme_cluster);
            }
            current_style.set_terminal_attributes(&mut self.terminal);
            write!(self.terminal, "{}", buffer).expect("write leftover buffer contents");
        }
        let _ = self.terminal.flush();
    }
}

impl<'a, T: Write + AsRawFd> Drop for Terminal<'a, T> {
    fn drop(&mut self) {
        let _ = self.leave_tui();
    }
}

pub mod test {
    use super::super::{
        GraphemeCluster, Height, Style, StyledGraphemeCluster, Width, Window, WindowBuffer,
    };

    /// A fake terminal that can be used in tests to create windows and compare the resulting
    /// contents to the expected contents of windows.
    #[derive(PartialEq)]
    pub struct FakeTerminal {
        values: WindowBuffer,
    }
    impl FakeTerminal {
        /// Create a window with the specified (width, height).
        pub fn with_size((w, h): (u32, u32)) -> Self {
            FakeTerminal {
                values: WindowBuffer::new(
                    Width::new(w as i32).unwrap(),
                    Height::new(h as i32).unwrap(),
                ),
            }
        }

        /// Create a fake terminal from a format string that looks roughly like this:
        ///
        /// "1 1 2 2 3 3 4 4"
        ///
        /// Spaces and newlines are ignored and the string is coerced into the specified size.
        pub fn from_str(
            (w, h): (u32, u32),
            description: &str,
        ) -> Result<Self, ::ndarray::ShapeError> {
            let mut tiles = Vec::<StyledGraphemeCluster>::new();
            for c in GraphemeCluster::all_from_str(description) {
                if c.as_str() == " " || c.as_str() == "\n" {
                    continue;
                }
                tiles.push(StyledGraphemeCluster::new(c, Style::plain()));
            }
            Ok(FakeTerminal {
                values: WindowBuffer::from_storage(::ndarray::Array2::from_shape_vec(
                    (h as usize, w as usize),
                    tiles,
                )?),
            })
        }

        /// Test if the terminal contents look like the given format string.
        /// The rows are separated by a "|".
        ///
        /// # Examples:
        ///
        /// ```
        /// use unsegen::base::terminal::test::FakeTerminal;
        /// use unsegen::base::GraphemeCluster;
        ///
        /// let mut term = FakeTerminal::with_size((2,3));
        /// {
        ///     let mut win = term.create_root_window();
        ///     win.fill(GraphemeCluster::try_from('_').unwrap());
        /// }
        ///
        /// term.assert_looks_like("__|__|__");
        /// ```
        pub fn assert_looks_like(&self, string_description: &str) {
            assert_eq!(format!("{:?}", self), string_description);
        }

        /// Create a root window that covers the whole terminal grid.
        pub fn create_root_window(&mut self) -> Window {
            self.values.as_window()
        }
    }

    impl ::std::fmt::Debug for FakeTerminal {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            let raw_values = self.values.storage();
            for r in 0..raw_values.dim().0 {
                for c in 0..raw_values.dim().1 {
                    let c = raw_values.get((r, c)).expect("debug: in bounds");
                    write!(f, "{}", c.grapheme_cluster.as_str())?;
                }
                if r != raw_values.dim().0 - 1 {
                    write!(f, "|")?;
                }
            }
            Ok(())
        }
    }
}