2021-03-19 16:36:02 -04:00
|
|
|
package terminal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-03-19 17:08:19 -04:00
|
|
|
"golang.org/x/term"
|
2021-03-24 16:23:17 -04:00
|
|
|
"os"
|
2021-03-19 16:36:02 -04:00
|
|
|
)
|
|
|
|
|
2021-03-25 12:27:48 -04:00
|
|
|
type Screen struct {
|
|
|
|
Rows int
|
|
|
|
Cols int
|
|
|
|
}
|
|
|
|
|
2021-03-24 16:23:17 -04:00
|
|
|
// Get the size of the terminal in rows and columns
|
2021-03-25 12:27:48 -04:00
|
|
|
func Size () *Screen {
|
|
|
|
cols := 80
|
|
|
|
rows := 24
|
2021-03-24 16:23:17 -04:00
|
|
|
|
|
|
|
// Try the syscall first
|
|
|
|
cols, rows, err := term.GetSize(int(os.Stdin.Fd()))
|
|
|
|
if err == nil {
|
2021-03-25 12:27:48 -04:00
|
|
|
return &Screen {rows, cols }
|
2021-03-19 16:36:02 -04:00
|
|
|
}
|
|
|
|
|
2021-03-24 16:23:17 -04:00
|
|
|
// Figure out the size the hard way
|
2021-03-31 19:17:04 -04:00
|
|
|
if term.IsTerminal(int(os.Stdin.Fd())) {
|
|
|
|
rows, cols = sizeTrick()
|
|
|
|
}
|
2021-03-19 16:36:02 -04:00
|
|
|
|
2021-03-25 12:27:48 -04:00
|
|
|
return &Screen{ rows, cols }
|
2021-03-19 16:36:02 -04:00
|
|
|
}
|
|
|
|
|
2021-03-24 13:24:40 -04:00
|
|
|
func sizeTrick () (rows int, cols int) {
|
|
|
|
// Move cursor to location further than likely screen size
|
|
|
|
// The cursor will move to maximum available position
|
2021-03-26 12:01:17 -04:00
|
|
|
fmt.Print(Code("999C") + Code("999B"))
|
2021-03-24 13:24:40 -04:00
|
|
|
|
|
|
|
// Ask the terminal where the cursor is
|
2021-03-26 12:01:17 -04:00
|
|
|
fmt.Print(LocateCursor)
|
2021-03-24 13:24:40 -04:00
|
|
|
|
|
|
|
// Read stdin looking for the reported location
|
|
|
|
buffer := ""
|
|
|
|
for char, _ := ReadKey(); char != 'R'; char, _ = ReadKey() {
|
|
|
|
|
|
|
|
if char == '\x1b' || char == '[' {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if char == 'R' || char == '\x00'{
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
buffer += string(char)
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := fmt.Sscanf(buffer, "%d;%d", &rows, &cols)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return rows, cols
|
2021-03-24 16:23:17 -04:00
|
|
|
}
|