Skip to content

Commit

Permalink
term: obtain the cursor position via termios.h (#11372)
Browse files Browse the repository at this point in the history
  • Loading branch information
AAAA committed Sep 6, 2021
1 parent 78c26e6 commit af28d09
Show file tree
Hide file tree
Showing 19 changed files with 190 additions and 123 deletions.
12 changes: 12 additions & 0 deletions vlib/os/os.c.v
Expand Up @@ -1008,3 +1008,15 @@ pub fn glob(patterns ...string) ?[]string {
matches.sort()
return matches
}

pub fn last_error() IError {
$if windows {
code := int(C.GetLastError())
msg := get_error_msg(code)
return error_with_code(msg, code)
} $else {
code := C.errno
msg := posix_get_error_msg(code)
return error_with_code(msg, code)
}
}
12 changes: 0 additions & 12 deletions vlib/readline/readline.v
Expand Up @@ -7,18 +7,6 @@
//
module readline

// Termios stores the terminal options on Linux.
struct C.termios {}

struct Termios {
mut:
c_iflag int
c_oflag int
c_cflag int
c_lflag int
c_cc [12]int // NCCS == 12. Can't use the defined value here
}

// Winsize stores the screen information on Linux.
struct Winsize {
ws_row u16
Expand Down
4 changes: 3 additions & 1 deletion vlib/readline/readline_default.c.v
Expand Up @@ -10,7 +10,9 @@ module readline

import os

#include <termios.h>
struct Termios {
}

// Only use standard os.get_line
// Need implementation for readline capabilities
//
Expand Down
64 changes: 47 additions & 17 deletions vlib/readline/readline_linux.c.v
Expand Up @@ -13,9 +13,32 @@ import os
#include <termios.h>
#include <sys/ioctl.h>

const cclen = 10

// Termios stores the terminal options on Linux.
struct C.termios {
mut:
c_iflag int
c_oflag int
c_cflag int
c_lflag int
c_line byte
c_cc [cclen]int
}

struct Termios {
mut:
c_iflag u32
c_oflag u32
c_cflag u32
c_lflag u32
c_line byte
c_cc [cclen]int
}

fn C.tcgetattr(fd int, termios_p &C.termios) int

fn C.tcsetattr(fd int, optional_actions int, termios_p &C.termios) int
fn C.tcsetattr(fd int, optional_actions int, const_termios_p &C.termios) int

fn C.raise(sig int)

Expand Down Expand Up @@ -47,18 +70,22 @@ enum Action {
// Please note that `enable_raw_mode` catches the `SIGUSER` (CTRL + C) signal.
// For a method that does please see `enable_raw_mode_nosig`.
pub fn (mut r Readline) enable_raw_mode() {
if C.tcgetattr(0, unsafe { &C.termios(&r.orig_termios) }) == -1 {
if unsafe { C.tcgetattr(0, &C.termios(&r.orig_termios)) } != 0 {
r.is_tty = false
r.is_raw = false
return
}
mut raw := r.orig_termios
mut raw := C.termios{}
unsafe { vmemcpy(&raw, &r.orig_termios, int(sizeof(raw))) }
// println('> r.orig_termios: $r.orig_termios')
// println('> raw: $raw')
raw.c_iflag &= ~(C.BRKINT | C.ICRNL | C.INPCK | C.ISTRIP | C.IXON)
raw.c_cflag |= C.CS8
raw.c_lflag &= ~(C.ECHO | C.ICANON | C.IEXTEN | C.ISIG)
raw.c_cc[C.VMIN] = 1
raw.c_cc[C.VTIME] = 0
C.tcsetattr(0, C.TCSADRAIN, unsafe { &C.termios(&raw) })
raw.c_cc[C.VMIN] = byte(1)
raw.c_cc[C.VTIME] = byte(0)
unsafe { C.tcsetattr(0, C.TCSADRAIN, &raw) }
// println('> after raw: $raw')
r.is_raw = true
r.is_tty = true
}
Expand All @@ -68,18 +95,19 @@ pub fn (mut r Readline) enable_raw_mode() {
// Please note that `enable_raw_mode_nosig` does not catch the `SIGUSER` (CTRL + C) signal
// as opposed to `enable_raw_mode`.
pub fn (mut r Readline) enable_raw_mode_nosig() {
if C.tcgetattr(0, unsafe { &C.termios(&r.orig_termios) }) == -1 {
if unsafe { C.tcgetattr(0, &C.termios(&r.orig_termios)) } != 0 {
r.is_tty = false
r.is_raw = false
return
}
mut raw := r.orig_termios
mut raw := C.termios{}
unsafe { vmemcpy(&raw, &r.orig_termios, int(sizeof(raw))) }
raw.c_iflag &= ~(C.BRKINT | C.ICRNL | C.INPCK | C.ISTRIP | C.IXON)
raw.c_cflag |= C.CS8
raw.c_lflag &= ~(C.ECHO | C.ICANON | C.IEXTEN)
raw.c_cc[C.VMIN] = 1
raw.c_cc[C.VTIME] = 0
C.tcsetattr(0, C.TCSADRAIN, unsafe { &C.termios(&raw) })
raw.c_cc[C.VMIN] = byte(1)
raw.c_cc[C.VTIME] = byte(0)
unsafe { C.tcsetattr(0, C.TCSADRAIN, &raw) }
r.is_raw = true
r.is_tty = true
}
Expand All @@ -88,7 +116,7 @@ pub fn (mut r Readline) enable_raw_mode_nosig() {
// For a description of raw mode please see the `enable_raw_mode` method.
pub fn (mut r Readline) disable_raw_mode() {
if r.is_raw {
C.tcsetattr(0, C.TCSADRAIN, unsafe { &C.termios(&r.orig_termios) })
unsafe { C.tcsetattr(0, C.TCSADRAIN, &C.termios(&r.orig_termios)) }
r.is_raw = false
}
}
Expand Down Expand Up @@ -122,7 +150,7 @@ pub fn (mut r Readline) read_line_utf8(prompt string) ?[]rune {
}
print(r.prompt)
for {
C.fflush(C.stdout)
unsafe { C.fflush(C.stdout) }
c := r.read_char()
a := r.analyse(c)
if r.execute(a, c) {
Expand Down Expand Up @@ -311,7 +339,7 @@ fn (mut r Readline) execute(a Action, c int) bool {
// get_screen_columns returns the number of columns (`width`) in the terminal.
fn get_screen_columns() int {
ws := Winsize{}
cols := if C.ioctl(1, C.TIOCGWINSZ, &ws) == -1 { 80 } else { int(ws.ws_col) }
cols := if unsafe { C.ioctl(1, C.TIOCGWINSZ, &ws) } == -1 { 80 } else { int(ws.ws_col) }
return cols
}

Expand Down Expand Up @@ -542,10 +570,12 @@ fn (mut r Readline) suspend() {
r.disable_raw_mode()
if !is_standalone {
// We have to SIGSTOP the parent v process
ppid := C.getppid()
C.kill(ppid, C.SIGSTOP)
unsafe {
ppid := C.getppid()
C.kill(ppid, C.SIGSTOP)
}
}
C.raise(C.SIGSTOP)
unsafe { C.raise(C.SIGSTOP) }
r.enable_raw_mode()
r.refresh_line()
if r.is_tty {
Expand Down
2 changes: 1 addition & 1 deletion vlib/readline/readline_test.v
Expand Up @@ -5,7 +5,7 @@ fn no_lines(s string) string {
}

fn test_struct_readline() {
// mut rl := Readline{}
// mut rl := readline.Readline{}
// eprintln('rl: $rl')
// line := rl.read_line('Please, enter your name: ') or { panic(err) }
// eprintln('line: $line')
Expand Down
4 changes: 4 additions & 0 deletions vlib/readline/readline_windows.c.v
Expand Up @@ -10,6 +10,10 @@ module readline

import os

// needed for parity with readline_default.c.v
struct Termios {
}

// Only use standard os.get_line
// Need implementation for readline capabilities
//
Expand Down
10 changes: 10 additions & 0 deletions vlib/term/declarations_default.c.v
@@ -0,0 +1,10 @@
module term

pub struct C.termios {
mut:
c_iflag int
c_oflag int
c_cflag int
c_lflag int
c_cc [10]int
}
11 changes: 11 additions & 0 deletions vlib/term/declarations_linux.c.v
@@ -0,0 +1,11 @@
module term

pub struct C.termios {
mut:
c_iflag int
c_oflag int
c_cflag int
c_lflag int
c_line byte
c_cc [10]int
}
94 changes: 43 additions & 51 deletions vlib/term/term_nix.c.v
Expand Up @@ -13,6 +13,10 @@ pub:
ws_ypixel u16
}

fn C.tcgetattr(fd int, ptr &C.termios) int

fn C.tcsetattr(fd int, action int, const_ptr &C.termios)

fn C.ioctl(fd int, request u64, arg voidptr) int

// get_terminal_size returns a number of colums and rows of terminal window.
Expand All @@ -21,70 +25,58 @@ pub fn get_terminal_size() (int, int) {
return default_columns_size, default_rows_size
}
w := C.winsize{}
C.ioctl(1, u64(C.TIOCGWINSZ), &w)
unsafe { C.ioctl(1, u64(C.TIOCGWINSZ), &w) }
return int(w.ws_col), int(w.ws_row)
}

// get_cursor_position returns a Coord containing the current cursor position
pub fn get_cursor_position() Coord {
pub fn get_cursor_position() ?Coord {
if os.is_atty(1) <= 0 || os.getenv('TERM') == 'dumb' {
return Coord{
x: 0
y: 0
}
return Coord{0, 0}
}
// TODO: use termios.h, C.tcgetattr & C.tcsetattr directly,
// instead of using `stty`
mut oldsettings := os.execute('stty -g')
if oldsettings.exit_code < 0 {
oldsettings = os.Result{}

old_state := C.termios{}
if unsafe { C.tcgetattr(0, &old_state) } != 0 {
return os.last_error()
}
os.system('stty -echo -icanon time 0')
print('\033[6n')
mut ch := int(0)
mut i := 0
// ESC [ YYY `;` XXX `R`
mut reading_x := false
mut reading_y := false
defer {
// restore the old terminal state:
unsafe { C.tcsetattr(0, C.TCSANOW, &old_state) }
}

mut state := C.termios{}
if unsafe { C.tcgetattr(0, &state) } != 0 {
return os.last_error()
}
state.c_lflag &= int(~(u32(C.ICANON) | u32(C.ECHO)))
unsafe { C.tcsetattr(0, C.TCSANOW, &state) }

print('\e[6n')

mut x := 0
mut y := 0
mut stage := byte(0)

// ESC [ YYY `;` XXX `R`

for {
ch = C.getchar()
b := byte(ch)
i++
if i >= 15 {
panic('C.getchar() called too many times')
}
// state management:
if b == `R` {
w := unsafe { C.getchar() }
if w < 0 {
return error_with_code('Failed to read from stdin', 888)
} else if w == `[` || w == `;` {
stage++
} else if `0` <= w && w <= `9` {
match stage {
// converting string values to int:
1 { y = y * 10 + int(w - `0`) }
2 { x = x * 10 + int(w - `0`) }
else {}
}
} else if w == `R` {
break
}
if b == `[` {
reading_y = true
reading_x = false
continue
}
if b == `;` {
reading_y = false
reading_x = true
continue
}
// converting string vals to ints:
if reading_x {
x *= 10
x += (b - byte(`0`))
}
if reading_y {
y *= 10
y += (b - byte(`0`))
}
}
// restore the old terminal settings:
os.system('stty $oldsettings.output')
return Coord{
x: x
y: y
}
return Coord{x, y}
}

// set_terminal_title change the terminal title
Expand Down
10 changes: 5 additions & 5 deletions vlib/term/term_test.v
Expand Up @@ -57,23 +57,23 @@ fn test_header() {
assert term_width == term.header('1234', '_-/\\/\\').len
}

fn test_get_cursor_position() {
original_position := term.get_cursor_position()
cursor_position_1 := term.get_cursor_position()
fn test_get_cursor_position() ? {
original_position := term.get_cursor_position() ?
cursor_position_1 := term.get_cursor_position() ?
assert original_position.x == cursor_position_1.x
assert original_position.y == cursor_position_1.y
//
term.set_cursor_position(
x: 10
y: 11
)
cursor_position_2 := term.get_cursor_position()
cursor_position_2 := term.get_cursor_position() ?
//
term.set_cursor_position(
x: 5
y: 6
)
cursor_position_3 := term.get_cursor_position()
cursor_position_3 := term.get_cursor_position() ?
//
term.set_cursor_position(original_position)
eprintln('original_position: $original_position')
Expand Down
4 changes: 3 additions & 1 deletion vlib/term/term_windows.c.v
Expand Up @@ -69,13 +69,15 @@ pub fn get_terminal_size() (int, int) {
}

// get_cursor_position returns a Coord containing the current cursor position
pub fn get_cursor_position() Coord {
pub fn get_cursor_position() ?Coord {
mut res := Coord{}
if os.is_atty(1) > 0 && os.getenv('TERM') != 'dumb' {
info := C.CONSOLE_SCREEN_BUFFER_INFO{}
if C.GetConsoleScreenBufferInfo(C.GetStdHandle(C.STD_OUTPUT_HANDLE), &info) {
res.x = info.dwCursorPosition.X
res.y = info.dwCursorPosition.Y
} else {
return os.last_error()
}
}
return res
Expand Down
7 changes: 3 additions & 4 deletions vlib/term/ui/color.v
Expand Up @@ -4,10 +4,9 @@

module ui

const (
value_range = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]!
color_table = init_color_table()
)
const value_range = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]!

pub const color_table = init_color_table()

[direct_array_access]
fn init_color_table() []int {
Expand Down

0 comments on commit af28d09

Please sign in to comment.