console.cpp 16 KB

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