-
Notifications
You must be signed in to change notification settings - Fork 0
/
painter.go
97 lines (83 loc) · 1.5 KB
/
painter.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
/*
* Copyright (c) 2023 Brandon Jordan
*/
package ttuy
import (
"fmt"
"strings"
"time"
)
var content string
var lineCount int
var lines []string
var lastContent string
var lastLineCount int
var diff int
type Template func() string
var stopPaint = make(chan bool)
// Painter prints and updates content received from Template
// Learn more: https://github.com/electrikmilk/ttuy/wiki/Painter()
func Painter(callback Template) {
lastContent = ""
lastLineCount = 0
currentLine = 0
content = callback()
CursorHide()
splitCount()
for {
select {
case <-stopPaint:
fmt.Println(content)
CursorShow()
return
default:
if currentLine != 0 {
BackUp()
}
content = callback()
if content != lastContent {
splitCount()
paint()
storeLast()
}
}
time.Sleep(50 * time.Millisecond)
}
}
func makeRoom() {
fmt.Print(strings.Repeat(eol, lineCount))
LinePrev(lineCount)
}
func paint() {
if lastLineCount < lineCount {
makeRoom()
}
for _, line := range lines {
replaceLine(line)
LineNext(1)
}
if lastLineCount == 0 || lastLineCount < lineCount {
return
}
diff = lastLineCount - lineCount
for i := 0; i < diff; i++ {
ClearLine()
LineNext(1)
}
}
func replaceLine(line string) {
ClearLine()
fmt.Print(line)
}
func splitCount() {
lines = strings.Split(content, eol)
lineCount = len(lines)
}
func storeLast() {
lastContent = content
lastLineCount = lineCount
}
// StopPainting triggers current usage of Painter to stop
func StopPainting() {
stopPaint <- true
}