Skip to content

Commit 3b646d7

Browse files
radaretrufae
authored andcommitted
Improve RCons.setRaw error handling and fix initial state ##cons
1 parent b0ac0a8 commit 3b646d7

File tree

1 file changed

+22
-30
lines changed

1 file changed

+22
-30
lines changed

libr/cons/cons.c

+22-30
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@
88

99
R_LIB_VERSION (r_cons);
1010

11-
static R_TH_LOCAL int oldraw = -1;
11+
typedef struct {
12+
int oldraw; // 0 = not initialized, 1 = false, 2 = true
13+
} Console;
14+
15+
static R_TH_LOCAL Console G = {0};
16+
1217
static R_TH_LOCAL RConsContext r_cons_context_default = {0};
1318
static RCons g_cons_instance = {0};
1419
static R_TH_LOCAL RCons g_cons_instance_tls = {0};
@@ -1882,33 +1887,24 @@ R_API void r_cons_show_cursor(int cursor) {
18821887
#endif
18831888
}
18841889

1885-
/**
1886-
* void r_cons_set_raw( [0,1] )
1887-
*
1888-
* Change canonicality of the terminal
1889-
*
1890-
* For optimization reasons, there's no initialization flag, so you need to
1891-
* ensure that the make the first call to r_cons_set_raw() with '1' and
1892-
* the next calls ^= 1, so: 1, 0, 1, 0, 1, ...
1893-
*
1894-
* If you doesn't use this order you'll probably loss your terminal properties.
1895-
*
1896-
*/
18971890
R_API void r_cons_set_raw(bool is_raw) {
1898-
if (oldraw != -1) {
1899-
if (is_raw == oldraw) {
1891+
if (G.oldraw != 0) {
1892+
if (is_raw == G.oldraw - 1) {
19001893
return;
19011894
}
19021895
}
19031896
#if EMSCRIPTEN || __wasi__
19041897
/* do nothing here */
19051898
#elif R2__UNIX__
1906-
// enforce echo off
1899+
struct termios *term_mode;
19071900
if (is_raw) {
19081901
I->term_raw.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1909-
tcsetattr (0, TCSANOW, &I->term_raw);
1902+
term_mode = &I->term_raw;
19101903
} else {
1911-
tcsetattr (0, TCSANOW, &I->term_buf);
1904+
term_mode = &I->term_buf;
1905+
}
1906+
if (tcsetattr (0, TCSANOW, term_mode) == -1) {
1907+
return;
19121908
}
19131909
#elif R2__WINDOWS__
19141910
if (I->term_xterm) {
@@ -1918,24 +1914,20 @@ R_API void r_cons_set_raw(bool is_raw) {
19181914
}
19191915
free (stty);
19201916
}
1921-
if (is_raw) {
1922-
if (I->term_xterm) {
1923-
r_sandbox_system ("stty raw -echo", 1);
1924-
} else {
1925-
SetConsoleMode (h, I->term_raw);
1926-
}
1917+
if (I->term_xterm) {
1918+
const char *cmd = is_raw
1919+
? "stty raw -echo"
1920+
: "stty raw echo";
1921+
r_sandbox_system (cmd, 1);
19271922
} else {
1928-
if (I->term_xterm) {
1929-
r_sandbox_system ("stty -raw echo", 1);
1930-
} else {
1931-
SetConsoleMode (h, I->term_buf);
1923+
if (!SetConsoleMode (h, is_raw? I->term_raw: I->term_buf)) {
1924+
return;
19321925
}
19331926
}
19341927
#else
19351928
#warning No raw console supported for this platform
19361929
#endif
1937-
fflush (stdout);
1938-
oldraw = is_raw;
1930+
G.oldraw = is_raw + 1;
19391931
}
19401932

19411933
R_API void r_cons_set_utf8(bool b) {

0 commit comments

Comments
 (0)