-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathcommon.go
95 lines (84 loc) · 2.1 KB
/
common.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
package term
import (
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"golang.org/x/crypto/ssh/terminal"
)
var ecsi = "\033]"
var st = "\007"
var cellSizeOnce sync.Once
var cellWidth, cellHeight float64
var termWidth, termHeight int
func HasGraphicsSupport() bool {
return os.Getenv("TERM_PROGRAM") == "iTerm.app" || sixelEnabled
}
// ClearScrollback clears iTerm2 scrollback.
func ClearScrollback() {
if !sixelEnabled {
print(ecsi + "1337;ClearScrollback" + st)
}
}
// TermSize contains sizing information of the terminal.
type TermSize struct {
Row int
Col int
Width int
Height int
}
func initCellSize() {
s, err := terminal.MakeRaw(1)
if err != nil {
return
}
defer terminal.Restore(1, s)
if sixelEnabled {
fmt.Fprint(os.Stdout, "\033[14t")
fileSetReadDeadline(os.Stdout, time.Now().Add(time.Second))
defer fileSetReadDeadline(os.Stdout, time.Time{})
fmt.Fscanf(os.Stdout, "\033[4;%d;%dt", &termHeight, &termWidth)
return
}
fmt.Fprint(os.Stdout, ecsi+"1337;ReportCellSize"+st)
fileSetReadDeadline(os.Stdout, time.Now().Add(time.Second))
defer fileSetReadDeadline(os.Stdout, time.Time{})
fmt.Fscanf(os.Stdout, "\033]1337;ReportCellSize=%f;%f\033\\", &cellHeight, &cellWidth)
}
// Size gathers sizing information of the current session's controling terminal.
func Size() (size TermSize, err error) {
size.Col, size.Row, err = terminal.GetSize(1)
if err != nil {
return
}
cellSizeOnce.Do(initCellSize)
if termWidth > 0 && termHeight > 0 {
size.Width = int(termWidth/(size.Col-1)) * (size.Col - 1)
size.Height = int(termHeight/(size.Row-1)) * (size.Row - 1)
return
}
if cellWidth+cellHeight == 0 {
err = errors.New("cannot get terminal cell size")
}
size.Width, size.Height = size.Col*int(cellWidth), size.Row*int(cellHeight)
return
}
// Rows returns the number of rows for the controling terminal.
func Rows() (rows int, err error) {
_, rows, err = terminal.GetSize(1)
return
}
func NewImageWriter(width, height int) io.WriteCloser {
if sixelEnabled {
return &sixelWriter{
Width: width,
Height: height,
}
}
return &imageWriter{
Width: width,
Height: height,
}
}