Debian Codegraph @

Utilities/KWSys/ConsoleBuf.hxx.in

raw
1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
3 #ifndef @KWSYS_NAMESPACE@_ConsoleBuf_hxx
4 #define @KWSYS_NAMESPACE@_ConsoleBuf_hxx
5
6 #include <@KWSYS_NAMESPACE@/Configure.hxx>
7
8 #include <@KWSYS_NAMESPACE@/Encoding.hxx>
9
10 #include <cstring>
11 #include <iostream>
12 #include <sstream>
13 #include <stdexcept>
14 #include <streambuf>
15 #include <string>
16
17 #if defined(_WIN32)
18 # include <windows.h>
19 # if __cplusplus >= 201103L
20 # include <system_error>
21 # endif
22 #endif
23
24 namespace @KWSYS_NAMESPACE@ {
25 #if defined(_WIN32)
26
27 template <class CharT, class Traits = std::char_traits<CharT> >
28 class BasicConsoleBuf : public std::basic_streambuf<CharT, Traits>
29 {
30 public:
31 typedef typename Traits::int_type int_type;
32 typedef typename Traits::char_type char_type;
33
34 class Manager
35 {
36 public:
37 Manager(std::basic_ios<CharT, Traits>& ios, const bool err = false)
38 : m_consolebuf(0)
39 {
40 m_ios = &ios;
41 try {
42 m_consolebuf = new BasicConsoleBuf<CharT, Traits>(err);
43 m_streambuf = m_ios->rdbuf(m_consolebuf);
44 } catch (const std::runtime_error& ex) {
45 std::cerr << "Failed to create ConsoleBuf!" << std::endl
46 << ex.what() << std::endl;
47 };
48 }
49
50 BasicConsoleBuf<CharT, Traits>* GetConsoleBuf() { return m_consolebuf; }
51
52 void SetUTF8Pipes()
53 {
54 if (m_consolebuf) {
55 m_consolebuf->input_pipe_codepage = CP_UTF8;
56 m_consolebuf->output_pipe_codepage = CP_UTF8;
57 m_consolebuf->activateCodepageChange();
58 }
59 }
60
61 ~Manager()
62 {
63 if (m_consolebuf) {
64 delete m_consolebuf;
65 m_ios->rdbuf(m_streambuf);
66 }
67 }
68
69 private:
70 std::basic_ios<CharT, Traits>* m_ios;
71 std::basic_streambuf<CharT, Traits>* m_streambuf;
72 BasicConsoleBuf<CharT, Traits>* m_consolebuf;
73 };
74
75 BasicConsoleBuf(const bool err = false)
76 : flush_on_newline(true)
77 , input_pipe_codepage(0)
78 , output_pipe_codepage(0)
79 , input_file_codepage(CP_UTF8)
80 , output_file_codepage(CP_UTF8)
81 , m_consolesCodepage(0)
82 {
83 m_hInput = ::GetStdHandle(STD_INPUT_HANDLE);
84 checkHandle(true, "STD_INPUT_HANDLE");
85 if (!setActiveInputCodepage()) {
86 throw std::runtime_error("setActiveInputCodepage failed!");
87 }
88 m_hOutput = err ? ::GetStdHandle(STD_ERROR_HANDLE)
89 : ::GetStdHandle(STD_OUTPUT_HANDLE);
90 checkHandle(false, err ? "STD_ERROR_HANDLE" : "STD_OUTPUT_HANDLE");
91 if (!setActiveOutputCodepage()) {
92 throw std::runtime_error("setActiveOutputCodepage failed!");
93 }
94 _setg();
95 _setp();
96 }
97
98 ~BasicConsoleBuf() throw() { sync(); }
99
100 bool activateCodepageChange()
101 {
102 return setActiveInputCodepage() && setActiveOutputCodepage();
103 }
104
105 protected:
106 virtual int sync()
107 {
108 bool success = true;
109 if (m_hInput && m_isConsoleInput &&
110 ::FlushConsoleInputBuffer(m_hInput) == 0) {
111 success = false;
112 }
113 if (m_hOutput && !m_obuffer.empty()) {
114 const std::wstring wbuffer = getBuffer(m_obuffer);
115 if (m_isConsoleOutput) {
116 DWORD charsWritten;
117 success =
118 ::WriteConsoleW(m_hOutput, wbuffer.c_str(), (DWORD)wbuffer.size(),
119 &charsWritten, nullptr) == 0
120 ? false
121 : true;
122 } else {
123 DWORD bytesWritten;
124 std::string buffer;
125 success = encodeOutputBuffer(wbuffer, buffer);
126 if (success) {
127 success =
128 ::WriteFile(m_hOutput, buffer.c_str(), (DWORD)buffer.size(),
129 &bytesWritten, nullptr) == 0
130 ? false
131 : true;
132 }
133 }
134 }
135 m_ibuffer.clear();
136 m_obuffer.clear();
137 _setg();
138 _setp();
139 return success ? 0 : -1;
140 }
141
142 virtual int_type underflow()
143 {
144 if (this->gptr() >= this->egptr()) {
145 if (!m_hInput) {
146 _setg(true);
147 return Traits::eof();
148 }
149 if (m_isConsoleInput) {
150 // ReadConsole doesn't tell if there's more input available
151 // don't support reading more characters than this
152 wchar_t wbuffer[8192];
153 DWORD charsRead;
154 if (ReadConsoleW(m_hInput, wbuffer,
155 (sizeof(wbuffer) / sizeof(wbuffer[0])), &charsRead,
156 nullptr) == 0 ||
157 charsRead == 0) {
158 _setg(true);
159 return Traits::eof();
160 }
161 setBuffer(std::wstring(wbuffer, charsRead), m_ibuffer);
162 } else {
163 std::wstring wbuffer;
164 std::string strbuffer;
165 DWORD bytesRead;
166 LARGE_INTEGER size;
167 if (GetFileSizeEx(m_hInput, &size) == 0) {
168 _setg(true);
169 return Traits::eof();
170 }
171 char* buffer = new char[size.LowPart];
172 while (ReadFile(m_hInput, buffer, size.LowPart, &bytesRead, nullptr) ==
173 0) {
174 if (GetLastError() == ERROR_MORE_DATA) {
175 strbuffer += std::string(buffer, bytesRead);
176 continue;
177 }
178 _setg(true);
179 delete[] buffer;
180 return Traits::eof();
181 }
182 if (bytesRead > 0) {
183 strbuffer += std::string(buffer, bytesRead);
184 }
185 delete[] buffer;
186 if (!decodeInputBuffer(strbuffer, wbuffer)) {
187 _setg(true);
188 return Traits::eof();
189 }
190 setBuffer(wbuffer, m_ibuffer);
191 }
192 _setg();
193 }
194 return Traits::to_int_type(*this->gptr());
195 }
196
197 virtual int_type overflow(int_type ch = Traits::eof())
198 {
199 if (!Traits::eq_int_type(ch, Traits::eof())) {
200 char_type chr = Traits::to_char_type(ch);
201 m_obuffer += chr;
202 if ((flush_on_newline && Traits::eq(chr, '\n')) ||
203 Traits::eq_int_type(ch, 0x00)) {
204 sync();
205 }
206 return ch;
207 }
208 sync();
209 return Traits::eof();
210 }
211
212 public:
213 bool flush_on_newline;
214 UINT input_pipe_codepage;
215 UINT output_pipe_codepage;
216 UINT input_file_codepage;
217 UINT output_file_codepage;
218
219 private:
220 HANDLE m_hInput;
221 HANDLE m_hOutput;
222 std::basic_string<char_type> m_ibuffer;
223 std::basic_string<char_type> m_obuffer;
224 bool m_isConsoleInput;
225 bool m_isConsoleOutput;
226 UINT m_activeInputCodepage;
227 UINT m_activeOutputCodepage;
228 UINT m_consolesCodepage;
229 void checkHandle(bool input, std::string handleName)
230 {
231 if ((input && m_hInput == INVALID_HANDLE_VALUE) ||
232 (!input && m_hOutput == INVALID_HANDLE_VALUE)) {
233 std::string errmsg =
234 "GetStdHandle(" + handleName + ") returned INVALID_HANDLE_VALUE";
235 # if __cplusplus >= 201103L
236 throw std::system_error(::GetLastError(), std::system_category(),
237 errmsg);
238 # else
239 throw std::runtime_error(errmsg);
240 # endif
241 }
242 }
243 UINT getConsolesCodepage()
244 {
245 if (!m_consolesCodepage) {
246 m_consolesCodepage = GetConsoleCP();
247 if (!m_consolesCodepage) {
248 m_consolesCodepage = GetACP();
249 }
250 }
251 return m_consolesCodepage;
252 }
253 bool setActiveInputCodepage()
254 {
255 m_isConsoleInput = false;
256 switch (GetFileType(m_hInput)) {
257 case FILE_TYPE_DISK:
258 m_activeInputCodepage = input_file_codepage;
259 break;
260 case FILE_TYPE_CHAR:
261 // Check for actual console.
262 DWORD consoleMode;
263 m_isConsoleInput =
264 GetConsoleMode(m_hInput, &consoleMode) == 0 ? false : true;
265 if (m_isConsoleInput) {
266 break;
267 }
268 @KWSYS_NAMESPACE@_FALLTHROUGH;
269 case FILE_TYPE_PIPE:
270 m_activeInputCodepage = input_pipe_codepage;
271 break;
272 default:
273 return false;
274 }
275 if (!m_isConsoleInput && m_activeInputCodepage == 0) {
276 m_activeInputCodepage = getConsolesCodepage();
277 }
278 return true;
279 }
280 bool setActiveOutputCodepage()
281 {
282 m_isConsoleOutput = false;
283 switch (GetFileType(m_hOutput)) {
284 case FILE_TYPE_DISK:
285 m_activeOutputCodepage = output_file_codepage;
286 break;
287 case FILE_TYPE_CHAR:
288 // Check for actual console.
289 DWORD consoleMode;
290 m_isConsoleOutput =
291 GetConsoleMode(m_hOutput, &consoleMode) == 0 ? false : true;
292 if (m_isConsoleOutput) {
293 break;
294 }
295 @KWSYS_NAMESPACE@_FALLTHROUGH;
296 case FILE_TYPE_PIPE:
297 m_activeOutputCodepage = output_pipe_codepage;
298 break;
299 default:
300 return false;
301 }
302 if (!m_isConsoleOutput && m_activeOutputCodepage == 0) {
303 m_activeOutputCodepage = getConsolesCodepage();
304 }
305 return true;
306 }
307 void _setg(bool empty = false)
308 {
309 if (!empty) {
310 this->setg((char_type*)m_ibuffer.data(), (char_type*)m_ibuffer.data(),
311 (char_type*)m_ibuffer.data() + m_ibuffer.size());
312 } else {
313 this->setg((char_type*)m_ibuffer.data(),
314 (char_type*)m_ibuffer.data() + m_ibuffer.size(),
315 (char_type*)m_ibuffer.data() + m_ibuffer.size());
316 }
317 }
318 void _setp()
319 {
320 this->setp((char_type*)m_obuffer.data(),
321 (char_type*)m_obuffer.data() + m_obuffer.size());
322 }
323 bool encodeOutputBuffer(const std::wstring wbuffer, std::string& buffer)
324 {
325 if (wbuffer.size() == 0) {
326 buffer = std::string();
327 return true;
328 }
329 const int length =
330 WideCharToMultiByte(m_activeOutputCodepage, 0, wbuffer.c_str(),
331 (int)wbuffer.size(), nullptr, 0, nullptr, nullptr);
332 char* buf = new char[length];
333 const bool success =
334 WideCharToMultiByte(m_activeOutputCodepage, 0, wbuffer.c_str(),
335 (int)wbuffer.size(), buf, length, nullptr,
336 nullptr) > 0
337 ? true
338 : false;
339 buffer = std::string(buf, length);
340 delete[] buf;
341 return success;
342 }
343 bool decodeInputBuffer(const std::string buffer, std::wstring& wbuffer)
344 {
345 size_t length = buffer.length();
346 if (length == 0) {
347 wbuffer = std::wstring();
348 return true;
349 }
350 int actualCodepage = m_activeInputCodepage;
351 const char BOM_UTF8[] = { char(0xEF), char(0xBB), char(0xBF) };
352 const char* data = buffer.data();
353 const size_t BOMsize = sizeof(BOM_UTF8);
354 if (length >= BOMsize && std::memcmp(data, BOM_UTF8, BOMsize) == 0) {
355 // PowerShell uses UTF-8 with BOM for pipes
356 actualCodepage = CP_UTF8;
357 data += BOMsize;
358 length -= BOMsize;
359 }
360 const size_t wlength = static_cast<size_t>(MultiByteToWideChar(
361 actualCodepage, 0, data, static_cast<int>(length), nullptr, 0));
362 wchar_t* wbuf = new wchar_t[wlength];
363 const bool success =
364 MultiByteToWideChar(actualCodepage, 0, data, static_cast<int>(length),
365 wbuf, static_cast<int>(wlength)) > 0
366 ? true
367 : false;
368 wbuffer = std::wstring(wbuf, wlength);
369 delete[] wbuf;
370 return success;
371 }
372 std::wstring getBuffer(const std::basic_string<char> buffer)
373 {
374 return Encoding::ToWide(buffer);
375 }
376 std::wstring getBuffer(const std::basic_string<wchar_t> buffer)
377 {
378 return buffer;
379 }
380 void setBuffer(const std::wstring wbuffer, std::basic_string<char>& target)
381 {
382 target = Encoding::ToNarrow(wbuffer);
383 }
384 void setBuffer(const std::wstring wbuffer,
385 std::basic_string<wchar_t>& target)
386 {
387 target = wbuffer;
388 }
389
390 }; // BasicConsoleBuf class
391
392 typedef BasicConsoleBuf<char> ConsoleBuf;
393 typedef BasicConsoleBuf<wchar_t> WConsoleBuf;
394
395 #endif
396 } // KWSYS_NAMESPACE
397
398 #endif