-
Notifications
You must be signed in to change notification settings - Fork 0
/
size.go
106 lines (95 loc) · 2.31 KB
/
size.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//go:build !windows
// +build !windows
package vt100
import (
"errors"
"syscall"
"unsafe"
"github.com/xyproto/env/v2"
)
type winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
func TermWidth() uint {
ws := &winsize{}
// Thanks https://stackoverflow.com/a/16576712/131264
if retCode, _, _ := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws))); int(retCode) != -1 {
return uint(ws.Col)
}
if w := env.Int("COLS", 0); w > 0 {
return uint(w)
}
return uint(env.Int("COLUMNS", 79))
}
func TermHeight() uint {
ws := &winsize{}
// Thanks https://stackoverflow.com/a/16576712/131264
if retCode, _, _ := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws))); int(retCode) != -1 {
return uint(ws.Row)
}
return uint(env.Int("LINES", 25))
}
func TermSize() (uint, uint, error) {
ws := &winsize{}
// Thanks https://stackoverflow.com/a/16576712/131264
if retCode, _, _ := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws))); int(retCode) != -1 {
return uint(ws.Col), uint(ws.Row), nil
}
var w uint = 79
if cols := env.Int("COLS", 0); cols > 0 {
w = uint(cols)
} else if cols := env.Int("COLUMNS", 0); cols > 0 {
w = uint(cols)
}
h := uint(env.Int("LINES", 25))
if h == 0 || w == 0 {
return 0, 0, errors.New("columns or lines has been set to 0")
}
return w, h, nil
}
// Convenience function
func ScreenWidth() int {
return int(TermWidth())
}
// Convenience function
func ScreenHeight() int {
return int(TermHeight())
}
// Convenience function
func ScreenSize() (int, int) {
w, h, err := TermSize()
if err != nil {
return -1, -1
}
return int(w), int(h)
}
// Convenience function
func MustTermSize() (uint, uint) {
ws := &winsize{}
// Thanks https://stackoverflow.com/a/16576712/131264
if retCode, _, _ := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws))); int(retCode) != -1 {
return uint(ws.Col), uint(ws.Row)
}
var w uint = 79
if cols := env.Int("COLS", 0); cols > 0 {
w = uint(cols)
} else if cols := env.Int("COLUMNS", 0); cols > 0 {
w = uint(cols)
}
return w, uint(env.Int("LINES", 25))
}