Last active
June 22, 2018 21:44
-
-
Save bhaak/140cc3f274bd7882300be66e56e80f16 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <termios.h> | |
#include <fcntl.h> | |
#define EXIT_FAILURE 1 | |
int | |
check_utf8() { | |
int supports_utf8 = 0; | |
struct termios original; | |
/* store current tty settings */ | |
if (tcgetattr(STDIN_FILENO, &original) == -1) { | |
perror("check_utf8 get terminal settings"); | |
exit(EXIT_FAILURE); | |
} | |
/* set minimal raw mode */ | |
struct termios raw; | |
raw.c_iflag &= ~(ISTRIP | BRKINT | INPCK | IGNCR | INLCR | ICRNL | IXON | IXOFF | PARMRK); | |
raw.c_cflag &= ~PARENB; | |
raw.c_cflag |= CS8; | |
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); | |
raw.c_cc[VMIN] = 0; | |
raw.c_cc[VTIME] = 3; /* timeout of 0.3 seconds */ | |
raw.c_oflag &= ~(OPOST | OCRNL | ONLRET); | |
tcflush(STDIN_FILENO, TCIFLUSH); | |
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) { | |
perror("check_utf8 set raw mode"); | |
exit(EXIT_FAILURE); | |
} | |
/* output the non-breaking space character twice in raw UTF-8 */ | |
if (write(STDOUT_FILENO, "\r\n\xc2\xa0\xc2\xa0", 6) != 6) { | |
perror("check_utf8 test sequence"); | |
exit(EXIT_FAILURE); | |
} | |
/* request the terminal to report the cursor position */ | |
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) { | |
perror("check_utf8 cursor position"); | |
exit(EXIT_FAILURE); | |
} | |
tcdrain(STDOUT_FILENO); | |
/* parse terminal reply */ | |
char c, previous_char = '\0'; | |
while (read(STDIN_FILENO, &c, 1) == 1) { | |
printf("-%c-\n", c); | |
/* skip everything until the row column separator */ | |
if (previous_char == ';') { | |
/* column == 3 means UTF-8 is supported, | |
* non-supporting terminals will report the cursor position | |
* in column 5 */ | |
supports_utf8 = c == '3' ? 1 : 0; | |
/* disable read timeout */ | |
raw.c_cc[VTIME] = 0; | |
if (tcsetattr(STDIN_FILENO, TCSANOW, &raw) == -1) { | |
perror("check_utf8_console after test"); | |
//exit(EXIT_FAILURE); | |
} | |
} | |
previous_char = c; | |
} | |
/* restore previous terminal settings */ | |
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &original) == -1) { | |
perror("check_utf8_console restore terminal settings"); | |
exit(EXIT_FAILURE); | |
} | |
return supports_utf8; | |
} | |
int main() { | |
if (check_utf8()) { | |
printf("\nUTF-8 supported \xf0\x9f\x92\xa9\n"); | |
} else { | |
printf("\nUTF-8 not supported :-(\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment