-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisplayer_terminal.go
More file actions
109 lines (93 loc) · 2.26 KB
/
displayer_terminal.go
File metadata and controls
109 lines (93 loc) · 2.26 KB
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
107
108
109
package main
import (
"fmt"
"image/color"
"os"
"strings"
"syscall"
"time"
"unsafe"
)
const (
clearScreen = "\033[2J"
moveTopLeft = "\033[H"
reset = "\033[0m"
)
type TerminalDisplayer struct{}
func NewTerminalDisplayer() *TerminalDisplayer {
return &TerminalDisplayer{}
}
func (td *TerminalDisplayer) Display(message string, duration time.Duration, col color.Color) {
termWidth, _ := td.getTerminalSize()
fmt.Print(clearScreen + moveTopLeft)
ansiColor := td.convertColor(col)
borderColor := td.swapColor(col)
resetColor := reset
defer fmt.Print(resetColor)
/* add some empty lines */
fmt.Println()
fmt.Println()
fmt.Println()
fmt.Println()
fmt.Println()
fmt.Println()
lines := strings.Split(message, "\n")
maxLen := 0
for _, line := range lines {
if len(line) > maxLen {
maxLen = len(line)
}
}
boxWidth := maxLen + 2
leftPad := max((termWidth-(boxWidth+2))/2, 0)
padSpaces := func() string { return strings.Repeat(" ", leftPad) }
hyphen := strings.Repeat("-", boxWidth)
fmt.Printf("%s%s+%s+%s\n", padSpaces(), borderColor, hyphen, resetColor)
for _, line := range lines {
padded := line + strings.Repeat(" ", maxLen-len(line))
// | border | text | border |
fmt.Printf("%s%s|%s%s %s %s%s|%s\n",
padSpaces(),
borderColor,
resetColor,
ansiColor,
padded,
resetColor,
borderColor,
resetColor,
)
}
fmt.Printf("%s%s+%s+%s\n", padSpaces(), borderColor, hyphen, resetColor)
}
func (td *TerminalDisplayer) convertColor(c color.Color) string {
r, g, b, _ := c.RGBA()
r8, g8, b8 := uint8(r>>8), uint8(g>>8), uint8(b>>8)
return fmt.Sprintf("\033[38;2;%d;%d;%dm\033[48;2;0;0;0m", r8, g8, b8)
}
func (td *TerminalDisplayer) swapColor(c color.Color) string {
r, g, b, _ := c.RGBA()
r8, g8, b8 := uint8(r>>8), uint8(g>>8), uint8(b>>8)
return fmt.Sprintf("\033[48;2;%d;%d;%dm\033[38;2;0;0;0m", r8, g8, b8)
}
func (td *TerminalDisplayer) getTerminalSize() (width, height int) {
var dims struct {
rows, cols, x, y uint16
}
retCode, _, err := syscall.Syscall6(
syscall.SYS_IOCTL,
os.Stdout.Fd(),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(&dims)),
0, 0, 0,
)
if err != 0 || retCode != 0 {
return 80, 24
}
return int(dims.cols), int(dims.rows)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}