-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (92 loc) · 1.8 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
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/common-nighthawk/go-figure"
"github.com/eiannone/keyboard"
)
func formatDuration(d time.Duration) string {
d = d.Round(time.Second)
h := int(d.Hours())
m := int(d.Minutes()) % 60
s := int(d.Seconds()) % 60
if h > 0 {
return fmt.Sprintf("%d:%02d:%02d", h, m, s)
} else if m > 0 {
return fmt.Sprintf("%d:%02d", m, s)
} else {
return fmt.Sprintf("%d", s)
}
}
func clearScreen() {
fmt.Print("\033[2J")
fmt.Print("\033[H")
}
func hideCursor() {
fmt.Print("\033[?25l")
}
func showCursor() {
fmt.Print("\033[?25h")
}
func main() {
hideCursor()
defer showCursor()
// Set up clean exit to ensure cursor is shown again
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
showCursor()
os.Exit(1)
}()
if err := keyboard.Open(); err != nil {
panic(err)
}
defer keyboard.Close()
start := time.Now()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
paused := false
var pauseTime time.Time
var elapsed time.Duration
go func() {
for {
char, key, err := keyboard.GetKey()
if err != nil {
panic(err)
}
if key == keyboard.KeySpace {
paused = !paused
if paused {
pauseTime = time.Now()
} else {
start = start.Add(time.Since(pauseTime))
}
} else if char == 'q' || char == 'Q' {
showCursor()
os.Exit(0)
}
}
}()
for range ticker.C {
clearScreen()
if !paused {
elapsed = time.Since(start)
}
timeStr := formatDuration(elapsed)
color := "yellow"
if paused {
color = "red"
}
myFigure := figure.NewColorFigure(timeStr, "basic", color, true)
myFigure.Print()
if paused {
fmt.Println("\nPAUSED - Press SPACE to resume")
} else {
fmt.Println("\nRUNNING - Press SPACE to pause")
}
}
}