-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
454 lines (369 loc) · 9.01 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/caseymrm/menuet"
"github.com/ncruces/zenity"
)
// timerFinishedAudioFile specifies the audio file which is played once the timer is finished.
//
// This file should be in the same directory as this executable.
//
// The file is played by invoking 'ffplay'.
const timerFinishedAudioFile = "you-can-heal.mp3"
const (
secondsInMinute = 60
timeStep = time.Millisecond * 999
// timerFile is used to display the timers inside Emacs.
timerFile = "/Users/Gira/.tim/timers.org"
)
// caffeinatePID is apparently required because one can't pass arguments to properQuitMenuItem().
var caffeinatePID = 0
// lastCurrentTime is used to only write to timerFile when the display has changed.
var lastCurrentTime = ""
var informedEmacsOnLaunch = false
type countdown struct {
minutes int
seconds int
}
func totalSecondsToString(totalSeconds int) string {
in := nearestDisplayFine(totalSeconds)
m := in / secondsInMinute
s := in % secondsInMinute
out := fmt.Sprintf("%d%0.2d", m, s)
if m > 9 {
mm := nearestFineDown(m)
if mm <= 9 {
mm = 12
}
return fmt.Sprintf("%d°", mm)
}
if len(out) < 3 {
return "0" + out
}
return out
}
func toString(minutes, seconds int) string {
return totalSecondsToString(minutes*secondsInMinute + seconds)
}
func (c countdown) isOverTime() bool {
return c.minutes <= 0 && c.seconds <= 0
}
func (c *countdown) flipForOverTime() {
if c.minutes < 0 {
c.minutes = -c.minutes
}
if c.seconds < 0 {
c.seconds = -c.seconds
}
}
func sumDigits(number int) int {
sumResult := 0
for number != 0 {
remainder := number % 10
sumResult += remainder
number = number / 10
}
if sumResult > 9 {
return sumDigits(sumResult)
}
return sumResult
}
func nearestDisplayFine(totalSeconds int) int {
current := totalSeconds
for {
m := current / secondsInMinute
s := current % secondsInMinute
test := sumDigits(m) + sumDigits(s)
if isFine(test) {
return m*secondsInMinute + s
}
current += 1
}
}
func nearestFineDown(inp int) int {
curr := inp
for !isFine(curr) {
curr -= 1
}
return curr
}
func isFine(inp int) bool {
return inp%3 == 0
}
func getRemainingTime(endTime time.Time) countdown {
now := time.Now()
difference := endTime.Sub(now)
total := int64(difference.Seconds())
minutes := total / secondsInMinute
seconds := total % secondsInMinute
return countdown{
minutes: int(minutes),
seconds: int(seconds),
}
}
func properQuitMenuItem() []menuet.MenuItem {
return []menuet.MenuItem{
{
Text: "Proper Quit",
Clicked: func() {
exitAndKillCaffeinate(0)
},
},
}
}
func getNewTimersString(current string, pid int, currentTime string, writeOwnPid bool) string {
output := ""
pidS := strconv.Itoa(pid)
lines := strings.Split(strings.TrimSpace(current), "\n")
for _, line := range lines {
if !strings.HasPrefix(line, pidS+" ") {
linePid := strings.Split(line, " ")[0]
if isPidRunning(linePid) {
output += line + "\n"
}
}
}
if writeOwnPid {
output += pidS + " " + currentTime
}
return strings.TrimSpace(output)
}
func isPidRunning(pid string) bool {
cmd := exec.Command("ps", "-p", pid)
err := cmd.Run()
return err == nil
}
// writeToTimersFile fills timerFile with this layout:
//
// {pid} {time-to-display}
// {pid} {time-to-display}
// ...
//
// Every PID can only appear once in the file.
func writeToTimersFile(currentTime string, writeOwnPid bool) {
data, err := ioutil.ReadFile(timerFile)
if err != nil {
panic(err)
}
initial := string(data)
pid := os.Getpid()
f, err := os.OpenFile(timerFile, os.O_WRONLY|os.O_TRUNC, 0x666)
if err != nil {
panic(err)
}
_, err = f.WriteString(getNewTimersString(initial, pid, currentTime, writeOwnPid))
if err != nil {
err2 := f.Close()
if err2 != nil {
panic(err2)
}
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
// if writeOwnPid is false, the tim process is always about to quit
if !writeOwnPid {
informEmacsToCheckModeLine()
} else {
if !informedEmacsOnLaunch {
informEmacsToCheckModeLine()
informedEmacsOnLaunch = true
}
}
}
func countDown(startTime time.Time, timerName string, totalCount int) {
menuet.App().Label = fmt.Sprintf("%d", caffeinatePID)
menuet.App().Children = properQuitMenuItem
countDown := time.Duration(totalCount) * time.Second
doneOn := startTime.Add(countDown)
isOverTime := false
for {
remaining := getRemainingTime(doneOn)
menuString := ""
if isOverTime {
remaining.flipForOverTime()
str := toString(remaining.minutes, remaining.seconds)
if remaining.seconds >= 1 {
menuString = "-" + str
} else {
// to not display a minus for the zero time
menuString = str
}
} else {
str := toString(remaining.minutes, remaining.seconds)
menuString = str
}
title := menuString
if timerName != "" {
title = timerName + " " + title
}
if lastCurrentTime != title {
writeToTimersFile(title, true)
}
lastCurrentTime = title
menuet.App().SetMenuState(&menuet.MenuState{
Title: title,
})
if remaining.isOverTime() && !isOverTime {
isOverTime = true
go timerIsUp(totalCount)
}
time.Sleep(timeStep)
}
}
func playFinishedSound() {
exe, err := os.Executable()
if err != nil {
panic(err)
}
path := filepath.Dir(exe)
// #nosec
err = exec.Command("afplay", path+"/"+timerFinishedAudioFile).Run()
if err != nil {
panic(err)
}
}
func timerIsUp(totalCount int) {
killCaffeinate()
forHuman := totalSecondsToString(totalCount)
text := fmt.Sprintf("%s passed.", forHuman)
err := zenity.Notify(text,
zenity.Title("Timer is finished"),
zenity.Icon(zenity.InfoIcon))
if err != nil {
panic(err)
}
go playFinishedSound()
_, err = zenity.Info(text,
zenity.Title("Timer is finished"),
zenity.Icon(zenity.InfoIcon))
if err != nil {
panic(err)
}
writeToTimersFile("", false)
os.Exit(0)
}
func safeAtoi(s string) int {
if s == "" {
return 0
}
parsed, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return parsed
}
func parseStringCountToSeconds(s string) int {
if strings.Contains(s, ",") {
const inMinutesSecondsFormat = 2
parts := strings.Split(s, ",")
switch len(parts) {
case inMinutesSecondsFormat:
return nearestDisplayFine(safeAtoi(parts[0])*secondsInMinute + safeAtoi(parts[1]))
}
} else {
// just minutes
return nearestDisplayFine(safeAtoi(s) * secondsInMinute)
}
println(fmt.Sprintf("Problematic time format: %s\n", s))
printUsage()
os.Exit(1)
// the return value here is really not important
return -1
}
func printUsage() {
println("Usage:\n" +
" countdown {time option} {optional timer name}\n\n" +
"Valid time options are:\n" +
" ,15 (15 seconds)\n" +
" 30 (30 minutes)\n" +
" 30,45 (30 minutes and 45 seconds)")
}
// waitForStdinToQuit queries stdin for an Enter to abort the program.
//
// Using a signal notifier like: signal.Notify(c, os.Interrupt, syscall.SIGTERM)
// causes an internal crash with the menu bar C code and is not fixable.
func waitForStdinToQuit(startTime time.Time, totalSeconds int) {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Hit Enter to cancel > ")
_, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
doneOn := startTime.Add(time.Second * time.Duration(totalSeconds))
remaining := getRemainingTime(doneOn)
if remaining.isOverTime() {
remaining.flipForOverTime()
str := toString(remaining.minutes, remaining.seconds)
fmt.Printf("\n%s over time...\n", str)
} else {
str := toString(remaining.minutes, remaining.seconds)
fmt.Printf("\n%s left...\n", str)
}
exitAndKillCaffeinate(0)
}
func killCaffeinate() {
// #nosec
cmd := exec.Command("kill", strconv.Itoa(caffeinatePID))
if err := cmd.Start(); err != nil {
panic(err)
}
// we do not check for errors here because the timer might have already been killed
_ = cmd.Wait()
}
func informEmacsToCheckModeLine() {
_ = exec.Command("timeout", "0.06", "emacsclient", "--eval", "(tim-mode-line-check)").Run()
}
func exitAndKillCaffeinate(exitCode int) {
writeToTimersFile("", false)
killCaffeinate()
os.Exit(exitCode)
}
// preventSystemSleepViaCaffeinate makes sure that the system does not
// idle sleep to keep the timer running correctly.
//
// This still allows the display to turn off.
func preventSystemSleepViaCaffeinate() {
cmd := exec.Command("caffeinate", "-i")
err := cmd.Start()
if err != nil {
panic(err)
}
pid := cmd.Process.Pid
go func() {
// when the timer is up, the caffeinate process is killed, so we do not check for errors here
_ = cmd.Wait()
}()
caffeinatePID = pid
}
func main() {
count := ""
const hasArg = 2
if len(os.Args) >= hasArg {
count = os.Args[1]
} else {
printUsage()
os.Exit(1)
}
startTime := time.Now()
countInSeconds := parseStringCountToSeconds(count)
preventSystemSleepViaCaffeinate()
go waitForStdinToQuit(startTime, countInSeconds)
timerName := ""
const hasTimerName = 3
if len(os.Args) >= hasTimerName {
timerName = os.Args[2]
}
go countDown(startTime, timerName, countInSeconds)
menuet.App().RunApplication()
}