| 57 | // |
| 58 | |
| 59 | void init(bool use_simple_io, bool use_advanced_display) { |
| 60 | advanced_display = use_advanced_display; |
| 61 | simple_io = use_simple_io; |
| 62 | #if defined(_WIN32) |
| 63 | // Windows-specific console initialization |
| 64 | DWORD dwMode = 0; |
| 65 | hConsole = GetStdHandle(STD_OUTPUT_HANDLE); |
| 66 | if (hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(hConsole, &dwMode)) { |
| 67 | hConsole = GetStdHandle(STD_ERROR_HANDLE); |
| 68 | if (hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(hConsole, &dwMode))) { |
| 69 | hConsole = nullptr; |
| 70 | simple_io = true; |
| 71 | } |
| 72 | } |
| 73 | if (hConsole) { |
| 74 | // Check conditions combined to reduce nesting |
| 75 | if (advanced_display && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) && |
| 76 | !SetConsoleMode(hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) { |
| 77 | advanced_display = false; |
| 78 | } |
| 79 | // Set console output codepage to UTF8 |
| 80 | SetConsoleOutputCP(CP_UTF8); |
| 81 | } |
| 82 | HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE); |
| 83 | if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) { |
| 84 | // Set console input codepage to UTF16 |
| 85 | _setmode(_fileno(stdin), _O_WTEXT); |
| 86 | |
| 87 | // Set ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT) |
| 88 | if (simple_io) { |
| 89 | dwMode |= ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT; |
| 90 | } else { |
| 91 | dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT); |
| 92 | } |
| 93 | if (!SetConsoleMode(hConIn, dwMode)) { |
| 94 | simple_io = true; |
| 95 | } |
| 96 | } |
| 97 | if (simple_io) { |
| 98 | _setmode(_fileno(stdin), _O_U8TEXT); |
| 99 | } |
| 100 | #else |
| 101 | // POSIX-specific console initialization |
| 102 | if (!simple_io) { |
| 103 | struct termios new_termios; |
| 104 | tcgetattr(STDIN_FILENO, &initial_state); |
| 105 | new_termios = initial_state; |
| 106 | new_termios.c_lflag &= ~(ICANON | ECHO); |
| 107 | new_termios.c_cc[VMIN] = 1; |
| 108 | new_termios.c_cc[VTIME] = 0; |
| 109 | tcsetattr(STDIN_FILENO, TCSANOW, &new_termios); |
| 110 | |
| 111 | tty = fopen("/dev/tty", "w+"); |
| 112 | if (tty != nullptr) { |
| 113 | out = tty; |
| 114 | } |
| 115 | } |
| 116 | |