Skip to content

Instantly share code, notes, and snippets.

@smart--petea
Last active March 17, 2021 17:27
Show Gist options
  • Save smart--petea/36dbbb1f6820ef1d7cece2b92c39cf0b to your computer and use it in GitHub Desktop.
Save smart--petea/36dbbb1f6820ef1d7cece2b92c39cf0b to your computer and use it in GitHub Desktop.
//from stackoverflow
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int get_pos(int *y, int *x);
int main() {
int x = 0, y = 0;
get_pos(&y, &x);
printf("x:%d, y:%d\n", x, y);
return 0;
}
int get_pos(int *y, int *x) {
char buf[30] = {0};
int ret, i, pow;
char ch;
*y = 0; *x = 0;
struct termios term, restore;
tcgetattr(0, &term);
tcgetattr(0, &restore);
term.c_lflag &= ~(ICANON|ECHO);
tcsetattr(0, TCSANOW, &term);
write(1, "\033[6n", 4);
for (i = 0, ch = 0; ch != 'R'; i++)
{
ret = read(0, &ch, 1);
if (!ret) {
tcsetattr(0, TCSANOW, &restore);
fprintf(stderr, "getpos: error readin response!\n");
return 1;
}
buf[i] = ch;
//printf("buf[%d]: \t%c \t%d\n", i, ch, ch);
}
if (i < 2) {
tcsetattr(0, TCSANOW, &restore);
printf("i < 2\n");
return(1);
}
for ( i -= 2, pow = 1; buf[i] != ';'; i--, pow *= 10) {
*x = *x + (buf[i] - '0') * pow;
}
for ( i--, pow = 1; buf[i] != '['; i--, pow *= 10) {
*y = *y + (buf[i] - '0') * pow;
}
tcsetattr(0, TCSANOW, &restore);
return 0;
}
package main
import (
"fmt"
"os"
"golang.org/x/sys/unix"
"syscall"
)
func main() {
x, y := getCursorPos()
fmt.Printf("x=%d, y=%d\n", x, y)
}
func getCursorPos() (int, int) {
fd := os.Stdin.Fd()
var request uint = unix.TCGETS
term, err := unix.IoctlGetTermios(int(fd), request)
if err != nil {
panic(err)
}
restore, err := unix.IoctlGetTermios(int(fd), request)
if err != nil {
panic(err)
}
term.Lflag &^= (syscall.ICANON | syscall.ECHO)
err = unix.IoctlSetTermios(int(fd), unix.TCSETS, term)
if err != nil {
panic(err)
}
_, err = os.Stdout.Write([]byte("\033[6n"))
if err != nil {
panic(err)
}
var x, y int
var zeroes int = 1
var firstNumber bool = true
b := make([]byte, 1)
var a string
for {
_, err = os.Stdin.Read(b)
if err != nil {
panic(err)
}
a = a + string(b)
if b[0] == 'R' {
break
}
if b[0] == ';' {
firstNumber = false
zeroes = 1
}
if b[0] >= '0' && b[0] <= '9' {
if firstNumber {
x = x * zeroes + (int(b[0]) - int('0'))
} else {
y = y * zeroes + (int(b[0]) - int('0'))
}
zeroes *= 10
}
}
err = unix.IoctlSetTermios(int(fd), unix.TCSETS, restore)
if err != nil {
panic(err)
}
return x, y
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment