ConsoleBuf.hxx 11 KB

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