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
#![doc=include_str!("../README.md")]
//! - A good place to start is by looking in the [`widgets`] module.
//! - Most apps will start with [`run_app`]
#![doc(
    html_logo_url = "https://gitlab.com/john_t/tuviv/-/raw/master/icon.png",
    html_favicon_url = "https://gitlab.com/john_t/tuviv/-/raw/master/icon.png"
)]
#![deny(missing_docs, clippy::missing_docs_in_private_items)]

pub mod border;
pub mod prelude;
pub mod terminal;
use std::{
    error::Error,
    io::{self, stdout, Write},
};

use crossterm::event::EnableMouseCapture;
#[cfg(feature = "crossterm")]
use crossterm::{
    cursor,
    event::DisableMouseCapture,
    execute,
    terminal::{
        disable_raw_mode, enable_raw_mode, EnterAlternateScreen,
        LeaveAlternateScreen,
    },
};
use std::time::Duration;
pub use terminal::Buffer;
pub use terminal::*;
pub mod widgets;

pub use le;
use le::layout::{Rect, Vec2};

/// A type representing a widget.
type WidgetType<'a> = Box<dyn Widget + 'a>;

/// A base trait for all widgets - it extends from
/// `layout_engines` layout to allow for layout while having
/// a [`render`](Widget::render) function to write to a buffer.
pub trait Widget: le::Layout {
    /// Renders the widget to the writer
    fn render(&self, rect: Rect, buffer: &mut Buffer);
}

impl<T> Widget for &T
where
    T: Widget,
{
    fn render(&self, rect: Rect, buffer: &mut Buffer) {
        T::render(self, rect, buffer)
    }
}

/**
Runs a tuviv app

This sets up all the terminal

- It takes a function (or closure) that:
    - Takes a `crossterm::event::Event` as input
    - Returns:
        - `Ok(Some(W))` on sucess - thus rendering a widget
        - `Ok(None)` for a graceful closing of the application
        - `Err(e)` for an error - which is printed to the stderr by tuviv

- The generics are:
    - `W`: the widget this returns
    - `E`: the error type. Use [`Infallible`](std::convert::Infallible) if `FW` doesn't fail
    - `FW`: the funtion

- A simple example function would be:
 ```rust
run_app(|event| {
    // Allows for the app to be quit
    if let Event::Key(key) = event {
        if let KeyCode::Char('q') = key.code {
            return Ok(None);
        }
    }
    // Create a widget
    let w = Paragraph::label("Press q to to quit").centered();

    // This app never fails, so we return Infallible (`!`)
    Ok::<_, Infallible>(w)
})
```
*/
#[cfg(feature = "crossterm")]
pub fn run_app<
    W: Widget,
    E: Error,
    FW: FnMut(crossterm::event::Event) -> Result<Option<W>, E>,
>(
    mut func: FW,
) -> io::Result<()> {
    use crossterm::event::{self, Event};
    let mut app = App::new()?;

    let mut err = None;

    let mut first_time = true;

    // Run the thing
    loop {
        let res = if first_time {
            let (x, y) = crossterm::terminal::size()?;
            func(Event::Resize(x, y))
        } else {
            func(event::read()?)
        };
        match res {
            Ok(okay) => match okay {
                Some(w) => {
                    app.render_widget(&w)?;
                }
                None => break,
            },
            Err(e) => {
                err = Some(e);
                break;
            }
        }
        first_time = false;
    }

    if let Some(err) = err {
        eprintln!("Error: {}", err);
    }

    Ok(())
}

/// Runs an app on an individual frame for a given Duration
///
/// Mainly useful for testing layouts, see [`run_app`] for
/// a more useful function
///
/// This will setup the terminal
#[cfg(feature = "crossterm")]
pub fn render_frame<W: Widget>(w: &W, duration: Duration) -> io::Result<()> {
    use std::thread;

    let mut app = App::new()?;

    let _ = execute!(stdout(), DisableMouseCapture,);
    app.render_widget(w)?;
    thread::sleep(duration);

    Ok(())
}

/// A struct to run an app
///
/// Use this if `run_app` is too basic for your use case,
/// i.e. if you want to use `async`
#[cfg(feature = "crossterm")]
pub struct App {
    /// The previous buffer
    prev_buffer: Buffer,
}

#[cfg(feature = "crossterm")]
impl App {
    /// Creates a new `App`
    ///
    /// This will set up the crossterm environment.
    /// When this is dropped then it will restore
    /// the terminal environment
    pub fn new() -> io::Result<Self> {
        enable_raw_mode()?;
        execute!(
            stdout(),
            EnterAlternateScreen,
            EnableMouseCapture,
            cursor::Hide
        )?;

        // Ensure images can be rendered in tmux
        if std::env::var("tmux").is_ok() {
            std::process::Command::new("tmux")
                .args(["set", "-p", "allow-passthrough", "on"])
                .spawn()?
                .wait()?;
        }

        Ok(Self {
            prev_buffer: Buffer::new(Vec2::new(0, 0)),
        })
    }

    /// Renders a widget
    pub fn render_widget<W: Widget>(&mut self, w: W) -> io::Result<()> {
        let (x, y) = crossterm::terminal::size()?;
        let x = x as usize;
        let y = y as usize;
        let mut buffer = Buffer::new(Vec2::new(x, y));
        w.render(Rect::new(0, 0, x, y), &mut buffer);
        CrosstermBackend.finish(&buffer, &self.prev_buffer, &mut stdout())?;
        stdout().flush()?;
        self.prev_buffer = buffer;
        Ok(())
    }

    /// Renders a boxed widget
    pub fn render_widget_boxed<'a>(
        &mut self,
        w: Box<dyn Widget + 'a>,
    ) -> io::Result<()> {
        let (x, y) = crossterm::terminal::size()?;
        let x = x as usize;
        let y = y as usize;
        let mut buffer = Buffer::new(Vec2::new(x, y));
        w.render(Rect::new(0, 0, x, y), &mut buffer);
        CrosstermBackend.finish(&buffer, &self.prev_buffer, &mut stdout())?;
        stdout().flush()?;
        self.prev_buffer = buffer;
        Ok(())
    }
}

impl Drop for App {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = execute!(
            stdout(),
            LeaveAlternateScreen,
            DisableMouseCapture,
            cursor::Show
        );
    }
}