-
Notifications
You must be signed in to change notification settings - Fork 0
/
pompompom
executable file
·285 lines (245 loc) · 8.62 KB
/
pompompom
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
#!/bin/python3
# A small pomodoro app with a built-in queue
# Meant for focus, and throwing it away without much thought each day.
#
# If you want to have a blank list every day, delete ~/.poms and make it a directory
# Or you can press "C" to manually throw everything away.
#
# Released into the public domain by the author, Zachary Vance
import contextlib, datetime, os, readline, select, sys, termios, time, threading, tty, wave
from sys import stdout
CHIME = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chime.wav")
with contextlib.closing(wave.open(CHIME, 'rb')) as f:
CHIME_DURATION = f.getnframes() / float(f.getframerate())
POMODORO_DURATION = 20*60
ALERT_DURATION = 30
POMS_SAVE = os.path.expanduser("~/.pompompom")
POMS_LOG = os.path.expanduser("~/.pompompom-done.txt")
if os.path.isdir(POMS_SAVE):
today = datetime.date.today().strftime("%Y-%m-%d")
POMS_LOG = os.path.join(POMS_SAVE, "{}.done.txt".format(today))
POMS_SAVE = os.path.join(POMS_SAVE, "{}.txt".format(today))
inst = """
ENTER to do a pom DEL to delete a pom
N to add a new pom C to clear all poms
R to redo the last pom DOWN to skip a pom
Q exits
""".strip().split("\n")
pom_inst = """
SPACE to pause/unpause N to add a new pom
R to restart the timer Q to exit (and delete)
""".strip().split("\n")
# So we can write without an error:
# if get_key(0.1) in "abc"
# we add this as a signal value in place of None
UNUSED_KEY = "?"
COLORS = {
"red": "\x1b[31m",
"green": "\x1b[32m",
"blue": "\x1b[34m",
"grey": "\x1b[90m",
}
BCOLORS = {
"black": "\x1b[40m",
"red": "\x1b[41m",
"green": "\x1b[42m",
"blue": "\x1b[44m",
}
CURSOR_HIDE = "\x1b[?25l"
CURSOR_SHOW = "\x1b[?25h"
SAVE_TERM = "\x1b[?1049h\x1b[H"
RESTORE_TERM = "\x1b[?1049l\x1b[0m\x1b[?5l" + CURSOR_SHOW
def now():
return float(time.time())
# --------------- General UI -------------------
stdin = os.fdopen(sys.stdin.fileno(), 'rb', buffering=0)
def get_key(timeout=9999999, default=None):
"""
Return the pressed keyboard button as a string.
Note, sometimes buttons are more than one byte (ex. arrow keys)
The default value is returned ONLY if the optional timeout expires
"""
old_settings = termios.tcgetattr(stdin)
try:
tty.setraw(stdin)
rlist, _, _ = select.select([stdin], [], [], timeout)
if rlist:
kp = b""
while select.select([stdin], [], [], 0.1)[0]:
kp += stdin.read(1)
return kp.decode("utf8")
finally:
termios.tcsetattr(stdin, termios.TCSADRAIN, old_settings)
return default
def clear_screen():
stdout.write("\x1b[2J\x1b[H\x1b[?25l\x1b[?5l" + CURSOR_HIDE)
def bell():
stdout.write("\x07") # Bell -- may be audible or visual
# Visual bell manually
stdout.write("\x1b[?5h")
stdout.flush()
time.sleep(1)
stdout.write("\x1b[?5l")
stdout.flush()
time.sleep(1)
try:
from playsound import playsound
except ModuleNotFoundError:
playsound = lambda *a, **v: 1
def move (x, y):
stdout.write("\033[%d;%dH" % (y,x))
def blit(x, y, B, F, c):
move(x, y)
stdout.write(B)
stdout.write(F)
stdout.write(c)
def write_left(x1, y, text, color):
for dx, c in enumerate(text):
blit(x1 + 1 + dx, y, BCOLORS["black"], COLORS[color], c)
stdout.flush()
def write_centered(x1, x2, y, text, color):
sx = (x1 + x2 - len(text))//2
for i, c in enumerate(text):
blit(sx+i, y, BCOLORS["black"], COLORS[color], c)
stdout.flush()
def display_card(color, lines, label=""):
sw, sh = os.get_terminal_size()
width, height = max((len(x) for x in lines), default=0), len(lines)
if label:
label = " " + label + " "
width = max(width, len(label))
width, height = width + 6, height + 4
width = max(width, 15)
x1, y1 = (sw-width)//2, (sh-height)//2
x2, y2 = x1+width, y1+height
B, F, E = BCOLORS[color], COLORS[color], BCOLORS["black"]
for x in range(x1, x2):
blit(x, y1, B, F, " ")
blit(x, y2-1, B, F, " ")
for y in range(y1, y2):
blit(x1, y, B, F, " ")
blit(x2-1, y, B, F, " ")
if label:
write_centered(x1, x2, y1, label, color)
for dy, line in enumerate(lines):
write_left(x1 + 2, y1 + 2 + dy, line, color)
stdout.flush()
return x1+3, x2-2, y1+2, y2-1
def confirm(prompt):
clear_screen()
display_card("red", [prompt + " (Y/N)"])
while True:
kp = get_key()
if kp in "Yy": return True
if kp in "Nn\x03": return False
def question(title, color):
clear_screen()
width = os.get_terminal_size()[0]-10
x1, x2, y1, y2 = display_card(color, [" "*width], title)
move(x1, y1)
try:
stdout.write(CURSOR_SHOW)
return input()
except KeyboardInterrupt: return ""
# --------------- Program UI -------------------
def alarm():
def alarm_sound(stop_early, duration=ALERT_DURATION):
for i in range(int(duration / CHIME_DURATION)):
if stop_early.acquire(blocking=False):
stop_early.release()
playsound(CHIME, block=True)
def alarm_flash(stop_early):
while stop_early.acquire(blocking=False):
stop_early.release()
bell()
stop_early = threading.Semaphore()
threading.Thread(target=alarm_sound, args=[stop_early]).start()
threading.Thread(target=alarm_flash, args=[stop_early]).start()
kp = get_key()
stop_early.acquire()
return kp
def display_pom_card(task):
x1, x2, y1, y2 = display_card("green", [task, ""])
display_help(pom_inst)
return x1, x2, y2-2 # Timer location
def display_poms(poms):
return display_card("blue", poms, "pomodoros")
def display_help(inst):
sw, sh = os.get_terminal_size()
if sw < max(len(x) for x in inst) or sh < 10:
return
for i, line in enumerate(inst):
write_left(1, sh-len(inst)+i+1, line, "green")
def update_countdown(x1, x2, y, s):
m,s = s//60, (s%60)//1
write_centered(x1, x2, y, "%02d:%02d" % (m,s), "grey")
def waiting(poms):
clear_screen()
display_poms(poms)
display_help(inst)
return get_key()
# --------------- Program Logic ----------------
def do_pomodoro(poms, duration=POMODORO_DURATION):
end = now() + duration
pom = poms.pop(0)
try:
while (left := end - now()) > 0:
clear_screen()
x1, x2, y = display_pom_card(pom)
update_countdown(x1, x2, y, left)
kp = get_key(0.1, UNUSED_KEY)
if kp is None: continue
if kp in " ": # Pause the timer with space
# Space un-pauses, as does any successful action key
while (kp := get_key()) not in "QqRr n\x03": pass
end = left + now()
if kp in "qQrR\x03": return kp, pom
if kp in "n":
do_new(poms, len(poms))
kp = alarm()
except KeyboardInterrupt:
kp = "\x03"
kp = "q"
log_pomodoro_done(kp, pom)
return kp, pom
def do_new(poms, pos):
if new := question("new pomodoro", "green").strip():
poms.insert(pos, new)
return new
def save(poms):
with open(POMS_SAVE, "w") as f:
for pom in poms:
f.write(pom + "\n")
def load():
if not os.path.exists(POMS_SAVE): return []
with open(POMS_SAVE, "r") as f:
return [x.strip() for x in list(f) if x.strip() != ""]
def log_pomodoro_done(kp, task):
with open(POMS_LOG, "a") as f:
f.write("{} {}\n".format(kp, task))
if __name__ == '__main__':
poms, pom_last, pom_this = load(), None, None
stdout.write(SAVE_TERM)
while (kp := waiting(poms)) not in "Qq\x03": # Ctrl-C
pom_this, pom_last = None, pom_this
if kp in "Pp \r" and (poms or do_new(poms, 0)): # Enter
kp, pom_this = do_pomodoro(poms)
while kp in "Rr" and (pom_last := (pom_this or pom_last)):
poms.insert(0, pom_last)
kp, pom_this = do_pomodoro(poms)
if kp in "Cc" and poms and confirm("Really delete all pomodoros?"):
for pom in poms: log_pomodoro_done(kp, pom)
poms, latest_pomodoro = [], None
if kp in "N":
do_new(poms, 0)
if kp in "n":
do_new(poms, len(poms))
if kp in ["s", "\x1b[B", "\x1b[C"] and poms: # Left, Down
poms.append(poms.pop(0))
if kp in ["S", "\x1b[A", "\x1b[D"] and poms: # Right, Up
poms.insert(0, poms.pop())
if kp in ["D", "d", "\x08", "\x1b[3~"] and poms: # Del, Backspace
pom = poms.pop(0)
log_pomodoro_done(kp, pom)
save(poms)
stdout.write(RESTORE_TERM)