Skip to content

Commit

Permalink
Minor terminal tweaks
Browse files Browse the repository at this point in the history
- Hide cursor while running.
- Fix silent exit on write failure due to resizing the terminal.
- Replace 'u_' prefix with '_now' suffix to be less confusing.
  • Loading branch information
cgmb committed Feb 6, 2020
1 parent 702730c commit e24a28a
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 12 deletions.
7 changes: 4 additions & 3 deletions main.c
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,7 @@ void draw(buffer* buf) {
buffer_clear(buf);
reposition_cursor(buf);
draw_rows(buf);
hide_cursor(buf);
buffer_write(buf);
}

Expand All @@ -1081,7 +1082,7 @@ bool process_keypress() {
colorize();
}
} else if (c == 'q') {
u_clear_screen();
clear_screen_now();
return false;
}
return true;
Expand Down Expand Up @@ -1118,7 +1119,7 @@ void update_window_size() {
void handle_window_size_changed(int signal) {
(void)signal;
update_window_size();
u_clear_screen();
clear_screen_now();
}

struct timespec subtract(struct timespec lhs, struct timespec rhs) {
Expand Down Expand Up @@ -1163,7 +1164,7 @@ int main(int argc, char** argv) {
sim_init(in);

enable_raw_mode();
u_clear_screen();
clear_screen_now();
buffer buf = { 0, 0 };
draw(&buf);

Expand Down
14 changes: 6 additions & 8 deletions misc/terminal.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,11 @@
static struct termios g_orig_termios;

static void write_stdin(const void* buf, ssize_t count) {
ssize_t res = write(STDIN_FILENO, buf, count);
if (res != count) {
exit(1);
}
int result = write(STDIN_FILENO, buf, count);
(void)result; // todo: handle EINTR
}

void u_clear_screen() {
void clear_screen_now() {
write_stdin("\x1b[2J", 4); // clear
write_stdin("\x1b[H", 3); // reposition cursor
}
Expand All @@ -41,12 +39,12 @@ void show_cursor(buffer* buf) {
buffer_append(buf, "\x1b[?25h", 6);
}

void u_show_cursor() {
void show_cursor_now() {
write_stdin("\x1b[?25h", 6);
}

void die(const char* msg) {
u_clear_screen();
clear_screen_now();
perror(msg);
exit(1);
}
Expand All @@ -59,7 +57,7 @@ void disable_raw_mode() {

void enable_raw_mode() {
atexit(disable_raw_mode);
atexit(u_show_cursor);
atexit(show_cursor_now);
if (tcgetattr(STDIN_FILENO, &g_orig_termios) == -1) {
die("failed to enable raw mode");
}
Expand Down
2 changes: 1 addition & 1 deletion misc/terminal.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ void buffer_clear(buffer* buf);

void die(const char* msg);

void u_clear_screen();
void clear_screen_now();

void clear_screen(buffer* buf);
void reposition_cursor(buffer* buf);
Expand Down

0 comments on commit e24a28a

Please sign in to comment.