From 1fa5a0269b4ea8c78738372f36028d479f8e997a Mon Sep 17 00:00:00 2001 From: Aritra Sarkar Date: Wed, 17 Nov 2021 15:27:47 +0530 Subject: [PATCH] Restore cursor position --- ansilib/inc/ansi/common.h | 2 +- ansilib/inc/ansi/cursor.h | 1 + ansilib/src/ansi/cursor.c | 22 ++++++++++++++++++++++ src/main.c | 9 ++++++++- 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/ansilib/inc/ansi/common.h b/ansilib/inc/ansi/common.h index f09c11c..b2b3f18 100644 --- a/ansilib/inc/ansi/common.h +++ b/ansilib/inc/ansi/common.h @@ -1,6 +1,6 @@ #ifndef __ANSI_COMMON_H_ # define __ANSI_COMMON_H_ -# define CSI "\x1b[" +# define CSI "\x1b[" /* Control Sequence Introducer */ #endif /* __ANSI_COMMON_H_ */ diff --git a/ansilib/inc/ansi/cursor.h b/ansilib/inc/ansi/cursor.h index 489c09c..d9c4a84 100644 --- a/ansilib/inc/ansi/cursor.h +++ b/ansilib/inc/ansi/cursor.h @@ -5,6 +5,7 @@ typedef enum { LEFT, DOWN, UP, RIGHT } dir_t; +point_t get_cursor_pos(void); void move_cursor(point_t); void nudge_cursor(dir_t, uint32_t step); diff --git a/ansilib/src/ansi/cursor.c b/ansilib/src/ansi/cursor.c index 5c37b1a..78380f6 100644 --- a/ansilib/src/ansi/cursor.c +++ b/ansilib/src/ansi/cursor.c @@ -1,10 +1,32 @@ #include #include +#include +#include #include #include #include +point_t get_cursor_pos(void) +{ + char buf[16]; + point_t ret = { 0 }; + + /* ESC[6n request cursor position (reports as ESC[#;#R) */ + + write(STDOUT_FILENO, CSI"6n", 4); + if ( read(STDIN_FILENO, buf, 16) ) { + + uint32_t line, column; + sscanf(buf, CSI"%"PRIu32"i;%"PRIu32"iR", &line, &column); + + ret.x = column; + ret.y = line; + } + + return ret; +} + void move_cursor(point_t pos) { char buf[16]; diff --git a/src/main.c b/src/main.c index f0d59af..f8be9cc 100644 --- a/src/main.c +++ b/src/main.c @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -68,7 +69,13 @@ int main(void) * } */ - draw_rectangle((point_t) { 2, 2 }, 32, 16); + /* save current cursor position */ + point_t orig_cursor_pos = get_cursor_pos(); + + draw_rectangle((point_t) { 20, 40 }, 32, 16); + + /* Return to the original cursor position */ + move_cursor(orig_cursor_pos); while ( 1 ) { -- 2.45.2