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
|
package cmd
import (
"log"
"time"
"github.com/gdamore/tcell/v2"
"github.com/spf13/cobra"
)
func drawTimer(scr tcell.Screen, time time.Duration, elapsed time.Duration, bgStyle, clockStyle tcell.Style) {
left := time-elapsed
if left<0{
left=0
bgStyle, clockStyle = clockStyle, bgStyle
}
// Clear the entire screen.
scr.SetStyle(bgStyle)
scr.Clear()
// Calculate square width/height and offset.
scrW, scrH := scr.Size()
// 17
// <--------------->
// ### ### ### ### ^
// # # # # # # # # # |
// # # # # # # # # | 5
// # # # # # # # # # |
// ### ### ### ### v
squareW := scrW / (17 + 2)
squareH := scrH / (5 + 2)
if squareH > squareW {
squareH = squareW
}
if squareW > squareH*3/2 {
squareW = squareH * 3 / 2
}
xOffset := (scrW - squareW*17) / 2
yOffset := (scrH - squareH*5) / 2
// Minute
minute := left.Minutes()
drawNumber(scr, int(minute)/10, xOffset+squareW*0, yOffset, squareW, squareH, clockStyle)
drawNumber(scr, int(minute)%10, xOffset+squareW*4, yOffset, squareW, squareH, clockStyle)
// Colon
drawSquare(scr, xOffset+squareW*8, yOffset+squareH*1, squareW, squareH, clockStyle)
drawSquare(scr, xOffset+squareW*8, yOffset+squareH*3, squareW, squareH, clockStyle)
// Second
second := left.Seconds()
drawNumber(scr, int(second)/10, xOffset+squareW*10, yOffset, squareW, squareH, clockStyle)
drawNumber(scr, int(second)%10, xOffset+squareW*14, yOffset, squareW, squareH, clockStyle)
}
func cmdTimer(cmd *cobra.Command, args []string) {
timerTime, err := time.ParseDuration(args[0])
if err != nil {
log.Fatalf("%+v", err)
}
bgStyle := tcell.StyleDefault.Background(tcell.ColorReset).Foreground(tcell.ColorReset)
clockStyle := tcell.StyleDefault.Foreground(tcell.ColorWhite).Background(tcell.ColorOlive)
scr, err := tcell.NewScreen()
if err != nil {
log.Fatalf("%+v", err)
}
if err := scr.Init(); err != nil {
log.Fatalf("%+v", err)
}
defer scr.Fini()
startTime := time.Now()
drawTimer(scr, timerTime, time.Now().Sub(startTime), bgStyle, clockStyle)
quitC := make(chan struct{})
go func() {
for {
scr.Show()
ev := scr.PollEvent()
switch ev := ev.(type) {
case *tcell.EventResize:
drawTimer(scr, timerTime, time.Now().Sub(startTime), bgStyle, clockStyle)
scr.Sync()
case *tcell.EventKey:
if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC || ev.Rune() == 'q' {
close(quitC)
return
}
}
}
}()
t := time.NewTicker(1 * time.Second)
defer t.Stop()
for {
select {
case <-quitC:
return
case now := <-t.C:
drawTimer(scr, timerTime, now.Sub(startTime), bgStyle, clockStyle)
scr.Show()
}
}
}
var timerCmd =&cobra.Command{
Use: "timer",
Short: "Timer mode",
Run: cmdTimer,
Args: cobra.ExactArgs(1),
}
|