-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
157 lines (135 loc) · 2.69 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package main
import (
"fmt"
"github.com/gdamore/tcell/v2"
"log"
random "math/rand"
"strings"
"time"
)
var rand *random.Rand
var shutdown = make(chan bool)
var active = true // TODO: get rid of this to avoid race conditions
func main() {
opts := options()
sc := newScreen()
var out string
quit := func() {
p := recover()
sc.Fini()
if p != nil {
panic(p)
}
if out != "" {
fmt.Println(out)
}
}
defer quit()
go func() {
for {
if !active {
<-shutdown
break
}
sc.Clear()
// default center position
px, py := opts.pot.ulPos(sc)
// align by moving 1/4 screen size
switch opts.align {
case left:
sw, _ := sc.Size()
px = px - (sw / 4)
case right:
sw, _ := sc.Size()
px = px + (sw / 4)
}
// user defined position overrides
if opts.baseX != 0 {
px = opts.baseX
}
if opts.baseY != 0 {
py = opts.baseY
}
// draw pot
opts.pot.draw(sc, px, py)
// draw from pot upwards
err := drawTree(sc, opts)
if err != nil {
log.Panicln(err.Error())
}
// draw message box
if opts.msg != "" {
sc.drawMessage(opts.msg, opts.msgX, opts.msgY)
}
// emit drawn event to trigger screen refresh
evDrawn(sc)
if opts.print {
// Store the tree for printing later,
// when screen cleanup is finished.
var tree []string
w, h := sc.Size()
for y := 0; y < h; y++ {
var sb strings.Builder
for x := 0; x < w; x++ {
r, _, _, _ := sc.GetContent(x, y)
sb.WriteRune(r)
}
s := sb.String()
// Ignore empty space above tree.
if strings.TrimSpace(s) != "" {
tree = append(tree, s)
}
}
out = strings.Join(tree, "\n")
// Send the quit event,
evQuit(sc)
// then wait for shutdown.
<-shutdown
break
}
if opts.infinite {
// We either await the delay or wait for shutdown.
select {
case <-shutdown:
return
case <-time.After(opts.wait):
}
} else {
// When not in infinite mode, we just
// draw 1 tree and wait for shutdown.
<-shutdown
}
}
}()
for {
switch ev := sc.PollEvent().(type) {
case *tcell.EventResize:
// resize event will be emitted once initially
sc.Sync()
case *tcell.EventKey:
if opts.screensaver {
evQuit(sc)
break
}
switch ev.Key() {
case tcell.KeyEscape:
evQuit(sc)
case tcell.KeyCtrlC:
// SIGINT
evQuit(sc)
case tcell.KeyCtrlD:
// SIGQUIT
evQuit(sc)
}
case *eventDrawn:
// finished drawing, show changes
sc.Show()
case *eventQuit:
active = false
// signal shutdown to main loop
shutdown <- true
// we can just exit here, the shutdown hook will clean up the terminal
return
}
}
}