| 246 | } |
| 247 | |
| 248 | static int put_codepoint(const char* utf8_codepoint, size_t length, int expectedWidth) { |
| 249 | #if defined(_WIN32) |
| 250 | CONSOLE_SCREEN_BUFFER_INFO bufferInfo; |
| 251 | if (!GetConsoleScreenBufferInfo(hConsole, &bufferInfo)) { |
| 252 | // go with the default |
| 253 | return expectedWidth; |
| 254 | } |
| 255 | COORD initialPosition = bufferInfo.dwCursorPosition; |
| 256 | DWORD nNumberOfChars = length; |
| 257 | WriteConsole(hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL); |
| 258 | |
| 259 | CONSOLE_SCREEN_BUFFER_INFO newBufferInfo; |
| 260 | GetConsoleScreenBufferInfo(hConsole, &newBufferInfo); |
| 261 | |
| 262 | // Figure out our real position if we're in the last column |
| 263 | if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) { |
| 264 | DWORD nNumberOfChars; |
| 265 | WriteConsole(hConsole, &" \b", 2, &nNumberOfChars, NULL); |
| 266 | GetConsoleScreenBufferInfo(hConsole, &newBufferInfo); |
| 267 | } |
| 268 | |
| 269 | int width = newBufferInfo.dwCursorPosition.X - initialPosition.X; |
| 270 | if (width < 0) { |
| 271 | width += newBufferInfo.dwSize.X; |
| 272 | } |
| 273 | return width; |
| 274 | #else |
| 275 | // We can trust expectedWidth if we've got one |
| 276 | if (expectedWidth >= 0 || tty == nullptr) { |
| 277 | fwrite(utf8_codepoint, length, 1, out); |
| 278 | return expectedWidth; |
| 279 | } |
| 280 | |
| 281 | fputs("\033[6n", tty); // Query cursor position |
| 282 | int x1; |
| 283 | int y1; |
| 284 | int x2; |
| 285 | int y2; |
| 286 | int results = 0; |
| 287 | results = fscanf(tty, "\033[%d;%dR", &y1, &x1); |
| 288 | |
| 289 | fwrite(utf8_codepoint, length, 1, tty); |
| 290 | |
| 291 | fputs("\033[6n", tty); // Query cursor position |
| 292 | results += fscanf(tty, "\033[%d;%dR", &y2, &x2); |
| 293 | |
| 294 | if (results != 4) { |
| 295 | return expectedWidth; |
| 296 | } |
| 297 | |
| 298 | int width = x2 - x1; |
| 299 | if (width < 0) { |
| 300 | // Calculate the width considering text wrapping |
| 301 | struct winsize w; |
| 302 | ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); |
| 303 | width += w.ws_col; |
| 304 | } |
| 305 | return width; |
no outgoing calls
no test coverage detected