console.cpp 16 KB

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