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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! Simple styled text streams.
//!
//! # Basic usage
//!
//! [`stdout()`](fn.stdout.html) and [`stderr()`](fn.stderr.html) are
//! drop-in replacements for `std::io::stdout()` and
//! `std::io::stderr()`, that wrap them in a
//! [`Stream`](trait.Stream.html) which supports eight foreground
//! colors and emphasized text.
//!
//! ### Example
//!
//! ```rust
//! use std::io::Write;
//! use stijl::{Stream, DoStyle, Red};
//!
//! # fn main() {
//! #     foo().unwrap();
//! # }
//! # fn foo() -> Result<(), Box<std::error::Error>> {
//! let str = &mut stijl::stdout(DoStyle::Auto);
//! str.fg(Red);
//! str.em();
//! write!(str, "Warning: ");
//! str.reset();
//! writeln!(str, " winter is coming.");
//! # Ok(())
//! # }
//! ```
//! # Platform notes
//!
//! [`stdout`](fn.stdout.html) and [`stderr`](fn.stderr.html) return a
//! `TermStream` object for terminals that understand terminfo-style
//! escape sequences, including the Cygwin and MSYS terminals, and the
//! Windows 10 console (Anniversary Update or newer). They return a
//! `ConStream` struct for consoles in earlier versions of Windows.
//!
//! # Multithreading
//!
//! The objects returned by [`stdout()`](fn.stdout.html) and
//! [`stderr()`](fn.stderr.html) implement
//! [`LockableStream`](trait.LockableStream.html).
//!
//! To reduce contention, multiple threads can write to their own
//! [`BufStream`](struct.BufStream.html) objects and when finished,
//! print them to a `LockableStream`.
//!
//! ### Example
//!
//! ```rust
//! use stijl::{BufStream, DoStyle};
//!
//! # fn main() {
//! #     foo().unwrap();
//! # }
//! # fn foo() -> Result<(), Box<std::error::Error>> {
//! let mut buf = BufStream::new();
//! // ...
//! // Do work
//! // Write to buf
//! // ...
//! let stream = &mut stijl::stdout(DoStyle::Auto);
//! let stream = &mut stream.lock();
//! buf.playback(stream)?;
//! # Ok(())
//! # }

#![allow(non_upper_case_globals)]
#![cfg_attr(feature = "cargo-clippy", allow(match_same_arms))]
#![cfg_attr(feature = "cargo-clippy", allow(match_bool))]

#[macro_use]
extern crate tinf;
#[macro_use]
extern crate lazy_static;

use std::{error, fmt, io};

#[cfg(windows)]
mod win32;
#[cfg(windows)]
mod console;
#[cfg(windows)]
pub use self::console::ConStream;

mod buf;
pub use self::buf::BufStream;
mod term;
pub use self::term::TermStream;


/// A [`LockableStream`](trait.LockableStream.html) wrapping `stdout`.
pub fn stdout(do_style: DoStyle) -> Box<LockableStream> {
    match terminal_mode(Handle::Stdout) {
        #[cfg(windows)]
        TerminalMode::Console => Box::new(ConStream::stdout(do_style)),
        mode => Box::new(TermStream::std(mode, io::stdout(), do_style)),
    }
}

/// A [`LockableStream`](trait.LockableStrem.html) wrapping `stderr`.
pub fn stderr(do_style: DoStyle) -> Box<LockableStream> {
    match terminal_mode(Handle::Stdout) {
        #[cfg(windows)]
        TerminalMode::Console => Box::new(ConStream::stderr(do_style)),
        mode => Box::new(TermStream::std(mode, io::stderr(), do_style)),
    }
}


#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
enum Handle {
    //Stdin = 0xfffffff6,
    Stdout = 0xfffffff5,
    Stderr = 0xfffffff4,
}

/// Strategies for applying styles to standard output streams.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DoStyle {
    /// Always apply styles.
    Always,
    /// Apply styles if stdout/stderr write to a terminal, but not if
    /// they are redirected.
    Auto,
    /// Never apply styles.
    Never,
}

/// A terminal color.
///
/// Values represent indexes in a terminal palette.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Color(i32, u16);

/// Color 0.
pub const Black: Color = Color(0, 0);
/// Color 1 (color 4 in Windows console)
pub const Red: Color = Color(1, 4);
/// Color 2
pub const Green: Color = Color(2, 2);
/// Color 3 (color 6 in Windows console)
pub const Yellow: Color = Color(3, 6);
/// Color 4 (color 1 in Windows console)
pub const Blue: Color = Color(4, 1);
/// Color 5
pub const Magenta: Color = Color(5, 5);
/// Color 6 (color 3 in Windows console)
pub const Cyan: Color = Color(6, 3);
/// Color 7
pub const White: Color = Color(7, 7);


/// An output stream with simple styling.
pub trait Stream: io::Write {
    /// Return color and emphasis to the default.
    fn reset(&mut self) -> Result<()>;
    /// Change the foreground color.
    fn fg(&mut self, fg: Color) -> Result<()>;
    /// Begin emphasized text.
    fn em(&mut self) -> Result<()>;
}

impl<'a> Stream for Box<Stream + 'a> {
    fn reset(&mut self) -> Result<()> {
        (**self).reset()
    }

    fn fg(&mut self, fg: Color) -> Result<()> {
        (**self).fg(fg)
    }

    fn em(&mut self) -> Result<()> {
        (**self).em()
    }
}

/// A [`Stream`](trait.Stream.html) with synchronized access.
pub trait LockableStream: Stream {
    /// Lock the stream, returning a writable guard.
    fn lock<'a>(&'a self) -> Box<Stream + 'a>;
}

impl Stream for Box<LockableStream> {
    fn reset(&mut self) -> Result<()> {
        (**self).reset()
    }

    fn fg(&mut self, fg: Color) -> Result<()> {
        (**self).fg(fg)
    }

    fn em(&mut self) -> Result<()> {
        (**self).em()
    }
}

/// An error that occurred writing to a `Stream`.
#[derive(Debug)]
pub struct Error(());

impl From<io::Error> for Error {
    fn from(_: io::Error) -> Error {
        // TODO
        Error(())
    }
}

impl From<::tinf::CapError> for Error {
    fn from(_: ::tinf::CapError) -> Error {
        // TODO
        Error(())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "TODO Error::fmt()")
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        "TODO Error::description()"
    }

    fn cause(&self) -> Option<&error::Error> {
        // TODO
        None
    }
}

/// Either success or failure.
pub type Result<T> = std::result::Result<T, Error>;


// Based on https://github.com/dtolnay/isatty.

enum TerminalMode {
    #[cfg(windows)]
    None,
    Redir,
    Term,
    #[cfg(windows)]
    Console,
    #[cfg(windows)]
    Win10,
}

#[cfg(not(windows))]
fn terminal_mode(handle: Handle) -> TerminalMode {
    extern crate libc;

    let handle = match handle {
        Handle::Stdout => libc::STDOUT_FILENO,
        Handle::Stderr => libc::STDERR_FILENO,
    };
    match unsafe { libc::isatty(handle) } {
        0 => TerminalMode::Redir,
        _ => TerminalMode::Term,
    }
}

#[cfg(windows)]
fn terminal_mode(handle: Handle) -> TerminalMode {
    use win32;

    let hndl = unsafe { win32::GetStdHandle(handle as u32) };
    match console_mode(hndl) {
        ConsoleMode::Default => return TerminalMode::Console,
        ConsoleMode::VT => return TerminalMode::Win10,
        ConsoleMode::None => (),
    }

    match msys_cygwin(hndl) {
        None => TerminalMode::None,
        Some(true) => TerminalMode::Term,
        Some(false) => TerminalMode::Redir,
    }
}

// Assumes console_mode(hndl) has already returned None.
#[cfg(windows)]
fn msys_cygwin(hndl: ::win32::Handle) -> Option<bool> {
    use std::os::windows::ffi::OsStringExt;

    let sz = ::std::mem::size_of::<win32::FileNameInfo>();
    let mut raw_info = vec![0u8; sz + win32::MAX_PATH];

    let ok = unsafe {
        ::win32::GetFileInformationByHandleEx(
            hndl,
            2,
            raw_info.as_mut_ptr() as *mut win32::Void,
            raw_info.len() as u32,
        )
    };
    if ok == 0 {
        return None;
    }

    let file_info =
        unsafe { *(raw_info[0..sz].as_ptr() as *const win32::FileNameInfo) };
    let name = &raw_info[sz..sz + file_info.file_name_length as usize];
    let name = unsafe {
        ::std::slice::from_raw_parts(
            name.as_ptr() as *const win32::WChar,
            name.len() / 2,
        )
    };
    let name = ::std::ffi::OsString::from_wide(name);
    let name = name.to_string_lossy();

    if name.starts_with("\\cygwin-") || name.starts_with("\\msys-") {
        Some(true)
    } else {
        Some(false)
    }
}

#[cfg(windows)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ConsoleMode {
    None,
    Default,
    VT,
}

#[cfg(windows)]
fn console_mode(hndl: ::win32::Handle) -> ConsoleMode {
    use win32;

    if hndl == win32::INVALID_HANDLE_VALUE {
        return ConsoleMode::None;
    }
    unsafe {
        let mut mode: u32 = 0;
        if 0 == win32::GetConsoleMode(hndl, &mut mode) {
            return ConsoleMode::None;
        }
        if (mode & win32::ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0 {
            return ConsoleMode::VT;
        }
        mode |= win32::ENABLE_VIRTUAL_TERMINAL_PROCESSING;
        if 0 == win32::SetConsoleMode(hndl, mode) {
            ConsoleMode::Default
        } else {
            ConsoleMode::VT
        }
    }
}

// Silences warning
lazy_static! {
}