1
0

console.cpp 16 KB

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