console.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. #include "console.h"
  2. #include <vector>
  3. #include <iostream>
  4. #if defined(_WIN32)
  5. #define WIN32_LEAN_AND_MEAN
  6. #ifndef NOMINMAX
  7. #define NOMINMAX
  8. #endif
  9. #include <windows.h>
  10. #include <fcntl.h>
  11. #include <io.h>
  12. #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
  13. #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
  14. #endif
  15. #else
  16. #include <climits>
  17. #include <sys/ioctl.h>
  18. #include <unistd.h>
  19. #include <wchar.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <signal.h>
  23. #include <termios.h>
  24. #endif
  25. #define ANSI_COLOR_RED "\x1b[31m"
  26. #define ANSI_COLOR_GREEN "\x1b[32m"
  27. #define ANSI_COLOR_YELLOW "\x1b[33m"
  28. #define ANSI_COLOR_BLUE "\x1b[34m"
  29. #define ANSI_COLOR_MAGENTA "\x1b[35m"
  30. #define ANSI_COLOR_CYAN "\x1b[36m"
  31. #define ANSI_COLOR_RESET "\x1b[0m"
  32. #define ANSI_BOLD "\x1b[1m"
  33. namespace console {
  34. //
  35. // Console state
  36. //
  37. static bool advanced_display = false;
  38. static bool simple_io = true;
  39. static display_t current_display = reset;
  40. static FILE* out = stdout;
  41. #if defined (_WIN32)
  42. static void* hConsole;
  43. #else
  44. static FILE* tty = nullptr;
  45. static termios initial_state;
  46. #endif
  47. //
  48. // Init and cleanup
  49. //
  50. void init(bool use_simple_io, bool use_advanced_display) {
  51. advanced_display = use_advanced_display;
  52. simple_io = use_simple_io;
  53. #if defined(_WIN32)
  54. // Windows-specific console initialization
  55. DWORD dwMode = 0;
  56. hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  57. if (hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(hConsole, &dwMode)) {
  58. hConsole = GetStdHandle(STD_ERROR_HANDLE);
  59. if (hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(hConsole, &dwMode))) {
  60. hConsole = nullptr;
  61. simple_io = true;
  62. }
  63. }
  64. if (hConsole) {
  65. // Check conditions combined to reduce nesting
  66. if (advanced_display && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) &&
  67. !SetConsoleMode(hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
  68. advanced_display = false;
  69. }
  70. // Set console output codepage to UTF8
  71. SetConsoleOutputCP(CP_UTF8);
  72. }
  73. HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
  74. if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) {
  75. // Set console input codepage to UTF16
  76. _setmode(_fileno(stdin), _O_WTEXT);
  77. // Set ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT)
  78. if (simple_io) {
  79. dwMode |= ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;
  80. } else {
  81. dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  82. }
  83. if (!SetConsoleMode(hConIn, dwMode)) {
  84. simple_io = true;
  85. }
  86. }
  87. #else
  88. // POSIX-specific console initialization
  89. if (!simple_io) {
  90. struct termios new_termios;
  91. tcgetattr(STDIN_FILENO, &initial_state);
  92. new_termios = initial_state;
  93. new_termios.c_lflag &= ~(ICANON | ECHO);
  94. new_termios.c_cc[VMIN] = 1;
  95. new_termios.c_cc[VTIME] = 0;
  96. tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
  97. tty = fopen("/dev/tty", "w+");
  98. if (tty != nullptr) {
  99. out = tty;
  100. }
  101. }
  102. setlocale(LC_ALL, "");
  103. #endif
  104. }
  105. void cleanup() {
  106. // Reset console display
  107. set_display(reset);
  108. #if !defined(_WIN32)
  109. // Restore settings on POSIX systems
  110. if (!simple_io) {
  111. if (tty != nullptr) {
  112. out = stdout;
  113. fclose(tty);
  114. tty = nullptr;
  115. }
  116. tcsetattr(STDIN_FILENO, TCSANOW, &initial_state);
  117. }
  118. #endif
  119. }
  120. //
  121. // Display and IO
  122. //
  123. // Keep track of current display and only emit ANSI code if it changes
  124. void set_display(display_t display) {
  125. if (advanced_display && current_display != display) {
  126. fflush(stdout);
  127. switch(display) {
  128. case reset:
  129. fprintf(out, ANSI_COLOR_RESET);
  130. break;
  131. case prompt:
  132. fprintf(out, ANSI_COLOR_YELLOW);
  133. break;
  134. case user_input:
  135. fprintf(out, ANSI_BOLD ANSI_COLOR_GREEN);
  136. break;
  137. case error:
  138. fprintf(out, ANSI_BOLD ANSI_COLOR_RED);
  139. }
  140. current_display = display;
  141. fflush(out);
  142. }
  143. }
  144. char32_t getchar32() {
  145. #if defined(_WIN32)
  146. HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
  147. wchar_t high_surrogate = 0;
  148. while (true) {
  149. INPUT_RECORD record;
  150. DWORD count;
  151. if (!ReadConsoleInputW(hConsole, &record, 1, &count) || count == 0) {
  152. return WEOF;
  153. }
  154. if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) {
  155. wchar_t wc = record.Event.KeyEvent.uChar.UnicodeChar;
  156. if (wc == 0) {
  157. continue;
  158. }
  159. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  160. high_surrogate = wc;
  161. continue;
  162. }
  163. if ((wc >= 0xDC00) && (wc <= 0xDFFF)) { // Check if wc is a low surrogate
  164. if (high_surrogate != 0) { // Check if we have a high surrogate
  165. return ((high_surrogate - 0xD800) << 10) + (wc - 0xDC00) + 0x10000;
  166. }
  167. }
  168. high_surrogate = 0; // Reset the high surrogate
  169. return static_cast<char32_t>(wc);
  170. }
  171. }
  172. #else
  173. wchar_t wc = getwchar();
  174. if (static_cast<wint_t>(wc) == WEOF) {
  175. return WEOF;
  176. }
  177. #if WCHAR_MAX == 0xFFFF
  178. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  179. wchar_t low_surrogate = getwchar();
  180. if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate
  181. return (static_cast<char32_t>(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000;
  182. }
  183. }
  184. if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair
  185. return 0xFFFD; // Return the replacement character U+FFFD
  186. }
  187. #endif
  188. return static_cast<char32_t>(wc);
  189. #endif
  190. }
  191. void pop_cursor() {
  192. #if defined(_WIN32)
  193. if (hConsole != NULL) {
  194. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  195. GetConsoleScreenBufferInfo(hConsole, &bufferInfo);
  196. COORD newCursorPosition = bufferInfo.dwCursorPosition;
  197. if (newCursorPosition.X == 0) {
  198. newCursorPosition.X = bufferInfo.dwSize.X - 1;
  199. newCursorPosition.Y -= 1;
  200. } else {
  201. newCursorPosition.X -= 1;
  202. }
  203. SetConsoleCursorPosition(hConsole, newCursorPosition);
  204. return;
  205. }
  206. #endif
  207. putc('\b', out);
  208. }
  209. int estimateWidth(char32_t codepoint) {
  210. #if defined(_WIN32)
  211. return 1;
  212. #else
  213. return wcwidth(codepoint);
  214. #endif
  215. }
  216. int put_codepoint(const char* utf8_codepoint, size_t length, int expectedWidth) {
  217. #if defined(_WIN32)
  218. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  219. if (!GetConsoleScreenBufferInfo(hConsole, &bufferInfo)) {
  220. // go with the default
  221. return expectedWidth;
  222. }
  223. COORD initialPosition = bufferInfo.dwCursorPosition;
  224. DWORD nNumberOfChars = length;
  225. WriteConsole(hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL);
  226. CONSOLE_SCREEN_BUFFER_INFO newBufferInfo;
  227. GetConsoleScreenBufferInfo(hConsole, &newBufferInfo);
  228. // Figure out our real position if we're in the last column
  229. if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) {
  230. DWORD nNumberOfChars;
  231. WriteConsole(hConsole, &" \b", 2, &nNumberOfChars, NULL);
  232. GetConsoleScreenBufferInfo(hConsole, &newBufferInfo);
  233. }
  234. int width = newBufferInfo.dwCursorPosition.X - initialPosition.X;
  235. if (width < 0) {
  236. width += newBufferInfo.dwSize.X;
  237. }
  238. return width;
  239. #else
  240. // We can trust expectedWidth if we've got one
  241. if (expectedWidth >= 0 || tty == nullptr) {
  242. fwrite(utf8_codepoint, length, 1, out);
  243. return expectedWidth;
  244. }
  245. fputs("\033[6n", tty); // Query cursor position
  246. int x1;
  247. int y1;
  248. int x2;
  249. int y2;
  250. int results = 0;
  251. results = fscanf(tty, "\033[%d;%dR", &y1, &x1);
  252. fwrite(utf8_codepoint, length, 1, tty);
  253. fputs("\033[6n", tty); // Query cursor position
  254. results += fscanf(tty, "\033[%d;%dR", &y2, &x2);
  255. if (results != 4) {
  256. return expectedWidth;
  257. }
  258. int width = x2 - x1;
  259. if (width < 0) {
  260. // Calculate the width considering text wrapping
  261. struct winsize w;
  262. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  263. width += w.ws_col;
  264. }
  265. return width;
  266. #endif
  267. }
  268. void replace_last(char ch) {
  269. #if defined(_WIN32)
  270. pop_cursor();
  271. put_codepoint(&ch, 1, 1);
  272. #else
  273. fprintf(out, "\b%c", ch);
  274. #endif
  275. }
  276. void append_utf8(char32_t ch, std::string & out) {
  277. if (ch <= 0x7F) {
  278. out.push_back(static_cast<unsigned char>(ch));
  279. } else if (ch <= 0x7FF) {
  280. out.push_back(static_cast<unsigned char>(0xC0 | ((ch >> 6) & 0x1F)));
  281. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  282. } else if (ch <= 0xFFFF) {
  283. out.push_back(static_cast<unsigned char>(0xE0 | ((ch >> 12) & 0x0F)));
  284. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  285. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  286. } else if (ch <= 0x10FFFF) {
  287. out.push_back(static_cast<unsigned char>(0xF0 | ((ch >> 18) & 0x07)));
  288. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 12) & 0x3F)));
  289. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  290. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  291. } else {
  292. // Invalid Unicode code point
  293. }
  294. }
  295. // Helper function to remove the last UTF-8 character from a string
  296. void pop_back_utf8_char(std::string & line) {
  297. if (line.empty()) {
  298. return;
  299. }
  300. size_t pos = line.length() - 1;
  301. // Find the start of the last UTF-8 character (checking up to 4 bytes back)
  302. for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) {
  303. if ((line[pos] & 0xC0) != 0x80) {
  304. break; // Found the start of the character
  305. }
  306. }
  307. line.erase(pos);
  308. }
  309. bool readline_advanced(std::string & line, bool multiline_input) {
  310. if (out != stdout) {
  311. fflush(stdout);
  312. }
  313. line.clear();
  314. std::vector<int> widths;
  315. bool is_special_char = false;
  316. bool end_of_stream = false;
  317. char32_t input_char;
  318. while (true) {
  319. fflush(out); // Ensure all output is displayed before waiting for input
  320. input_char = getchar32();
  321. if (input_char == '\r' || input_char == '\n') {
  322. break;
  323. }
  324. if (input_char == (char32_t) WEOF || input_char == 0x04 /* Ctrl+D*/) {
  325. end_of_stream = true;
  326. break;
  327. }
  328. if (is_special_char) {
  329. set_display(user_input);
  330. replace_last(line.back());
  331. is_special_char = false;
  332. }
  333. if (input_char == '\033') { // Escape sequence
  334. char32_t code = getchar32();
  335. if (code == '[' || code == 0x1B) {
  336. // Discard the rest of the escape sequence
  337. while ((code = getchar32()) != (char32_t) WEOF) {
  338. if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') {
  339. break;
  340. }
  341. }
  342. }
  343. } else if (input_char == 0x08 || input_char == 0x7F) { // Backspace
  344. if (!widths.empty()) {
  345. int count;
  346. do {
  347. count = widths.back();
  348. widths.pop_back();
  349. // Move cursor back, print space, and move cursor back again
  350. for (int i = 0; i < count; i++) {
  351. replace_last(' ');
  352. pop_cursor();
  353. }
  354. pop_back_utf8_char(line);
  355. } while (count == 0 && !widths.empty());
  356. }
  357. } else {
  358. int offset = line.length();
  359. append_utf8(input_char, line);
  360. int width = put_codepoint(line.c_str() + offset, line.length() - offset, estimateWidth(input_char));
  361. if (width < 0) {
  362. width = 0;
  363. }
  364. widths.push_back(width);
  365. }
  366. if (!line.empty() && (line.back() == '\\' || line.back() == '/')) {
  367. set_display(prompt);
  368. replace_last(line.back());
  369. is_special_char = true;
  370. }
  371. }
  372. bool has_more = multiline_input;
  373. if (is_special_char) {
  374. replace_last(' ');
  375. pop_cursor();
  376. char last = line.back();
  377. line.pop_back();
  378. if (last == '\\') {
  379. line += '\n';
  380. fputc('\n', out);
  381. has_more = !has_more;
  382. } else {
  383. // llama will just eat the single space, it won't act as a space
  384. if (line.length() == 1 && line.back() == ' ') {
  385. line.clear();
  386. pop_cursor();
  387. }
  388. has_more = false;
  389. }
  390. } else {
  391. if (end_of_stream) {
  392. has_more = false;
  393. } else {
  394. line += '\n';
  395. fputc('\n', out);
  396. }
  397. }
  398. fflush(out);
  399. return has_more;
  400. }
  401. bool readline_simple(std::string & line, bool multiline_input) {
  402. #if defined(_WIN32)
  403. std::wstring wline;
  404. if (!std::getline(std::wcin, wline)) {
  405. // Input stream is bad or EOF received
  406. line.clear();
  407. GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
  408. return false;
  409. }
  410. int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wline[0], (int)wline.size(), NULL, 0, NULL, NULL);
  411. line.resize(size_needed);
  412. WideCharToMultiByte(CP_UTF8, 0, &wline[0], (int)wline.size(), &line[0], size_needed, NULL, NULL);
  413. #else
  414. if (!std::getline(std::cin, line)) {
  415. // Input stream is bad or EOF received
  416. line.clear();
  417. return false;
  418. }
  419. #endif
  420. if (!line.empty()) {
  421. char last = line.back();
  422. if (last == '/') { // Always return control on '/' symbol
  423. line.pop_back();
  424. return false;
  425. }
  426. if (last == '\\') { // '\\' changes the default action
  427. line.pop_back();
  428. multiline_input = !multiline_input;
  429. }
  430. }
  431. line += '\n';
  432. // By default, continue input if multiline_input is set
  433. return multiline_input;
  434. }
  435. bool readline(std::string & line, bool multiline_input) {
  436. set_display(user_input);
  437. if (simple_io) {
  438. return readline_simple(line, multiline_input);
  439. }
  440. return readline_advanced(line, multiline_input);
  441. }
  442. }