]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/tty.rs
rollup merge of #20350: fhahn/issue-20340-rustdoc-version
[rust.git] / src / libstd / sys / windows / tty.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // ignore-lexer-test FIXME #15877
12
13 //! Windows specific console TTY implementation
14 //!
15 //! This module contains the implementation of a Windows specific console TTY.
16 //! Also converts between UTF-16 and UTF-8. Windows has very poor support for
17 //! UTF-8 and some functions will panic. In particular ReadFile and ReadConsole
18 //! will panic when the codepage is set to UTF-8 and a Unicode character is
19 //! entered.
20 //!
21 //! FIXME
22 //! This implementation does not account for codepoints that are split across
23 //! multiple reads and writes. Also, this implementation does not expose a way
24 //! to read/write UTF-16 directly. When/if Rust receives a Reader/Writer
25 //! wrapper that performs encoding/decoding, this implementation should switch
26 //! to working in raw UTF-16, with such a wrapper around it.
27
28 use super::c::{ReadConsoleW, WriteConsoleW, GetConsoleMode, SetConsoleMode};
29 use super::c::{ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS};
30 use super::c::{ENABLE_INSERT_MODE, ENABLE_LINE_INPUT};
31 use super::c::{ENABLE_PROCESSED_INPUT, ENABLE_QUICK_EDIT_MODE};
32 use libc::{c_int, HANDLE, LPDWORD, DWORD, LPVOID};
33 use libc::{get_osfhandle, CloseHandle};
34 use libc::types::os::arch::extra::LPCVOID;
35 use io::{mod, IoError, IoResult, MemReader};
36 use prelude::*;
37 use ptr;
38 use str::from_utf8;
39
40 use sys_common::unimpl;
41
42 fn invalid_encoding() -> IoError {
43     IoError {
44         kind: io::InvalidInput,
45         desc: "text was not valid unicode",
46         detail: None,
47     }
48 }
49
50 pub fn is_tty(fd: c_int) -> bool {
51     let mut out: DWORD = 0;
52     // If this function doesn't panic then fd is a TTY
53     match unsafe { GetConsoleMode(get_osfhandle(fd) as HANDLE,
54                                   &mut out as LPDWORD) } {
55         0 => false,
56         _ => true,
57     }
58 }
59
60 pub struct TTY {
61     closeme: bool,
62     handle: HANDLE,
63     utf8: MemReader,
64 }
65
66 impl TTY {
67     pub fn new(fd: c_int) -> IoResult<TTY> {
68         if is_tty(fd) {
69             // If the file descriptor is one of stdin, stderr, or stdout
70             // then it should not be closed by us
71             let closeme = match fd {
72                 0...2 => false,
73                 _ => true,
74             };
75             let handle = unsafe { get_osfhandle(fd) as HANDLE };
76             Ok(TTY {
77                 handle: handle,
78                 utf8: MemReader::new(Vec::new()),
79                 closeme: closeme,
80             })
81         } else {
82             Err(IoError {
83                 kind: io::MismatchedFileTypeForOperation,
84                 desc: "invalid handle provided to function",
85                 detail: None,
86             })
87         }
88     }
89
90     pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
91         // Read more if the buffer is empty
92         if self.utf8.eof() {
93             let mut utf16 = Vec::from_elem(0x1000, 0u16);
94             let mut num: DWORD = 0;
95             match unsafe { ReadConsoleW(self.handle,
96                                          utf16.as_mut_ptr() as LPVOID,
97                                          utf16.len() as u32,
98                                          &mut num as LPDWORD,
99                                          ptr::null_mut()) } {
100                 0 => return Err(super::last_error()),
101                 _ => (),
102             };
103             utf16.truncate(num as uint);
104             let utf8 = match String::from_utf16(utf16.as_slice()) {
105                 Ok(utf8) => utf8.into_bytes(),
106                 Err(..) => return Err(invalid_encoding()),
107             };
108             self.utf8 = MemReader::new(utf8);
109         }
110         // MemReader shouldn't error here since we just filled it
111         Ok(self.utf8.read(buf).unwrap())
112     }
113
114     pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
115         let utf16 = match from_utf8(buf).ok() {
116             Some(utf8) => {
117                 utf8.utf16_units().collect::<Vec<u16>>()
118             }
119             None => return Err(invalid_encoding()),
120         };
121         let mut num: DWORD = 0;
122         match unsafe { WriteConsoleW(self.handle,
123                                      utf16.as_ptr() as LPCVOID,
124                                      utf16.len() as u32,
125                                      &mut num as LPDWORD,
126                                      ptr::null_mut()) } {
127             0 => Err(super::last_error()),
128             _ => Ok(()),
129         }
130     }
131
132     pub fn set_raw(&mut self, raw: bool) -> IoResult<()> {
133         // FIXME
134         // Somebody needs to decide on which of these flags we want
135         match unsafe { SetConsoleMode(self.handle,
136             match raw {
137                 true => 0,
138                 false => ENABLE_ECHO_INPUT | ENABLE_EXTENDED_FLAGS |
139                          ENABLE_INSERT_MODE | ENABLE_LINE_INPUT |
140                          ENABLE_PROCESSED_INPUT | ENABLE_QUICK_EDIT_MODE,
141             }) } {
142             0 => Err(super::last_error()),
143             _ => Ok(()),
144         }
145     }
146
147     pub fn get_winsize(&mut self) -> IoResult<(int, int)> {
148         // FIXME
149         // Get console buffer via CreateFile with CONOUT$
150         // Make a CONSOLE_SCREEN_BUFFER_INFO
151         // Call GetConsoleScreenBufferInfo
152         // Maybe call GetLargestConsoleWindowSize instead?
153         Err(unimpl())
154     }
155 }
156
157 impl Drop for TTY {
158     fn drop(&mut self) {
159         if self.closeme {
160             // Nobody cares about the return value
161             let _ = unsafe { CloseHandle(self.handle) };
162         }
163     }
164 }