-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow
More file actions
executable file
·3822 lines (3489 loc) · 153 KB
/
Copy pathflow
File metadata and controls
executable file
·3822 lines (3489 loc) · 153 KB
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# /// script
# dependencies = []
# ///
# flow — focus timer · blocker · todo · ambient sounds
# zero external dependencies — pure python + curses
import sys
import os
import time
import math
import json
import random
import struct
import wave
import signal
import atexit
import threading
import subprocess
import shutil
import urllib.request
import re
import curses
import socket
try:
import pwd # Unix-only; absent on native Windows (the core TUI still runs there)
except ImportError:
pwd = None
from datetime import datetime, timedelta
import calendar as _calendar
# ==============================================================================
# PATHS
# ==============================================================================
def get_user_home():
sudo_user = os.environ.get("SUDO_USER")
if sudo_user and pwd is not None:
try:
return pwd.getpwnam(sudo_user).pw_dir
except Exception:
pass
return os.path.expanduser("~")
FLOW_DIR = os.path.join(get_user_home(), ".config", "flow")
SOUNDS_DIR = os.path.join(FLOW_DIR, "sounds")
CONFIG_PATH = os.path.join(FLOW_DIR, "config.json")
TASKS_PATH = os.path.join(FLOW_DIR, "tasks.json")
HABITS_PATH = os.path.join(FLOW_DIR, "habits.json")
MPV_SOCKET = f"/tmp/flow_mpv_{os.getpid()}"
CAVA_CONFIG = f"/tmp/flow_cava_{os.getpid()}.conf"
os.makedirs(SOUNDS_DIR, exist_ok=True)
# ==============================================================================
# SOLID BLOCK BANNER — "flow" in filled block characters
# ==============================================================================
FLOW_BANNER = [
"██████ ██ ██████ ██ ██",
"██ ██ ██ ██ ██ ██",
"█████ ██ ██ ██ ██ ██ ██",
"██ ██ ██ ██ ██████████",
"██ ███████ ██████ ██ ██ ",
]
# ==============================================================================
# BIG DIGIT FONT for timer (4 wide × 5 tall)
# ==============================================================================
DIGITS = {
"0": ["▄▀▀▄", "█ █", "█ █", "█ █", "▀▄▄▀"],
"1": [" ▄█ ", " █ ", " █ ", " █ ", " ▄█▄"],
"2": ["▄▀▀▄", " █", " ▄▄▀", "█ ", "█▄▄▄"],
"3": ["▄▀▀▄", " █", " ▀▀▄", " █", "▀▄▄▀"],
"4": ["█ █", "█ █", "▀▀▀█", " █", " █"],
"5": ["█▀▀▀", "█ ", "▀▀▀▄", " █", "▀▄▄▀"],
"6": ["▄▀▀▄", "█ ", "█▀▀▄", "█ █", "▀▄▄▀"],
"7": ["▀▀▀█", " █", " █ ", " █ ", " █ "],
"8": ["▄▀▀▄", "█ █", "▄▀▀▄", "█ █", "▀▄▄▀"],
"9": ["▄▀▀▄", "█ █", "▀▄▄█", " █", "▀▄▄▀"],
":": [" ", " ██ ", " ", " ██ ", " "],
}
# ==============================================================================
# SAFE CURSES WRITE — clips at boundaries, never crashes
# ==============================================================================
def saddstr(win, y, x, text, attr=0):
try:
my, mx = win.getmaxyx()
if y < 0 or y >= my or x >= mx:
return
avail = mx - x - 1
if avail <= 0:
return
win.addstr(y, x, text[:avail], attr)
except curses.error:
pass
# ==============================================================================
# CONFIG MANAGER
# ==============================================================================
class ConfigManager:
def __init__(self):
self.work_dur = 25
self.short_break_dur = 5
self.long_break_dur = 15
self.sessions_before_long = 4
self.sound_enabled = True
self.notifications = True
self.auto_start_work = False
self.auto_start_break = False
self.block_apps = False
self.clock_24h = True
self.blocked_apps = []
self.left_panel_width = 30
self.study_total = 0 # total study seconds (persistent)
self.daily_study = {} # {"YYYY-MM-DD": seconds} for the stats views
self.daily_goal_seconds = 7200 # 2h default daily focus goal
self.visualizer = True # bottom spectrum visualizer on/off
self.visualizer_rows = 2 # height of the visualizer strip (1-4)
self.vis_bars = 60 # cava bar count (20–100)
self.vis_amplitude = 100 # height scaling percent (25–150)
self.auto_start = False # auto-start the next focus/break automatically
self.pomodoro_target = 0 # planned focus sessions (0 = unlimited)
self.countdown_name = "" # label for the top-bar countdown
self.countdown_date = "" # "YYYY-MM-DD" target; "" disables it
self.load()
def load(self):
if os.path.exists(CONFIG_PATH):
try:
with open(CONFIG_PATH, "r") as f:
data = json.load(f)
# Clean legacy keys
data.pop("block_web", None)
data.pop("blocked_domains", None)
self.__dict__.update(data)
except Exception:
pass
def save(self):
try:
with open(CONFIG_PATH, "w") as f:
json.dump(self.__dict__, f, indent=2)
except Exception:
pass
# Settings that "Reset to Defaults" restores → their factory values. Kept as
# one explicit map so the reset can never drift from the __init__ defaults
# and so it touches *only* preferences — never user data (study_total,
# daily_study, blocked_apps).
RESET_DEFAULTS = {
"work_dur": 25,
"short_break_dur": 5,
"long_break_dur": 15,
"sessions_before_long": 4,
"daily_goal_seconds": 7200,
"auto_start": False,
"pomodoro_target": 0,
"countdown_name": "",
"countdown_date": "",
"sound_enabled": True,
"notifications": True,
"visualizer": True,
"visualizer_rows": 2,
"vis_bars": 60,
"vis_amplitude": 100,
"block_apps": False,
}
def reset_defaults(self):
"""Restore every tweakable preference to its factory value, leaving
accumulated data (focus history, blocked-app list) untouched."""
for key, val in self.RESET_DEFAULTS.items():
setattr(self, key, val)
self.save()
# ==============================================================================
# NESTED TODO MANAGER — unlimited subtask nesting support
# ==============================================================================
class TodoManager:
def __init__(self):
self.tasks = []
self.load()
def load(self):
if os.path.exists(TASKS_PATH):
try:
with open(TASKS_PATH, "r") as f:
raw = json.load(f)
self.tasks = self._normalize_tasks(raw)
except Exception:
self.tasks = []
def _normalize_tasks(self, task_list):
normalized = []
for t in task_list:
if not isinstance(t, dict):
continue
normalized.append({
"id": t.get("id", str(int(time.time() * 1000))),
"summary": t.get("summary", ""),
"done": t.get("done", t.get("completed", False)),
"expanded": t.get("expanded", True),
"subtasks": self._normalize_tasks(t.get("subtasks", []))
})
return normalized
def save(self):
try:
with open(TASKS_PATH, "w") as f:
json.dump(self.tasks, f, indent=2)
except Exception:
pass
def update_states(self):
def update_rec(tasks_list):
for t in tasks_list:
if t.get("subtasks"):
update_rec(t["subtasks"])
t["done"] = all(sub["done"] for sub in t["subtasks"])
update_rec(self.tasks)
def add(self, summary):
self.tasks.append({
"id": str(int(time.time() * 1000)),
"summary": summary,
"done": False,
"expanded": True,
"subtasks": []
})
self.update_states()
self.save()
def _get_node_by_path(self, path):
if not path:
return None
node = self.tasks[path[0]]
for idx in path[1:]:
node = node["subtasks"][idx]
return node
def toggle_by_path(self, path):
node = self._get_node_by_path(path)
if not node:
return
new_state = not node["done"]
def prop_down(n, state):
n["done"] = state
for sub in n.get("subtasks", []):
prop_down(sub, state)
prop_down(node, new_state)
self.update_states()
self.save()
def add_sibling_by_path(self, path, summary):
if not path:
self.add(summary)
return
if len(path) == 1:
self.tasks.insert(path[0] + 1, {
"id": str(int(time.time() * 1000)),
"summary": summary,
"done": False,
"expanded": True,
"subtasks": []
})
else:
parent = self._get_node_by_path(path[:-1])
if "subtasks" not in parent:
parent["subtasks"] = []
parent["subtasks"].insert(path[-1] + 1, {
"id": str(int(time.time() * 1000)),
"summary": summary,
"done": False,
"expanded": True,
"subtasks": []
})
self.update_states()
self.save()
def add_subtask_by_path(self, path, summary):
node = self._get_node_by_path(path)
if not node:
return
if "subtasks" not in node:
node["subtasks"] = []
node["subtasks"].append({
"id": str(int(time.time() * 1000)),
"summary": summary,
"done": False,
"expanded": True,
"subtasks": []
})
node["expanded"] = True
self.update_states()
self.save()
def delete_by_path(self, path):
if not path:
return
if len(path) == 1:
self.tasks.pop(path[0])
else:
parent = self._get_node_by_path(path[:-1])
parent["subtasks"].pop(path[-1])
self.update_states()
self.save()
def parse_duration_to_seconds(s):
"""'21h3m23s' / '2h' / '30m' / '90' (bare = minutes) -> seconds. 0 if invalid."""
s = (s or "").strip().lower()
if s.isdigit():
return int(s) * 60
total = 0
for val, unit in re.findall(r"(\d+)\s*([hms])", s):
total += int(val) * {"h": 3600, "m": 60, "s": 1}[unit]
return total
def get_visible_tasks(tasks, depth=0, path=None):
if path is None:
path = []
res = []
for idx, t in enumerate(tasks):
current_path = path + [idx]
res.append({
"task": t,
"depth": depth,
"path": current_path
})
if t.get("expanded", True) and t.get("subtasks"):
res.extend(get_visible_tasks(t["subtasks"], depth + 1, current_path))
return res
def count_all_tasks(tasks):
"""Count only top-level tasks, not subtasks."""
total = len(tasks)
done = sum(1 for t in tasks if t["done"])
return done, total
def count_subtasks(task):
subs = task.get("subtasks", [])
if not subs:
return 0, 0
done_cnt = 0
tot_cnt = 0
for s in subs:
tot_cnt += 1
if s["done"]:
done_cnt += 1
if s.get("subtasks"):
d, t = count_subtasks(s)
done_cnt += d
tot_cnt += t
return done_cnt, tot_cnt
# ==============================================================================
# HABIT MANAGER — daily habit tracking with streaks
# ==============================================================================
class HabitManager:
def __init__(self):
self.habits = [] # [{id, name, history: {"YYYY-MM-DD": true}}]
self.load()
def load(self):
if os.path.exists(HABITS_PATH):
try:
with open(HABITS_PATH, "r") as f:
raw = json.load(f)
out = []
for h in raw:
if not isinstance(h, dict):
continue
out.append({
"id": h.get("id", str(int(time.time() * 1000))),
"name": h.get("name", ""),
"history": h.get("history", {}) if isinstance(h.get("history"), dict) else {},
})
self.habits = out
except Exception:
self.habits = []
def save(self):
try:
with open(HABITS_PATH, "w") as f:
json.dump(self.habits, f, indent=2)
except Exception:
pass
@staticmethod
def today():
return datetime.now().strftime("%Y-%m-%d")
def add(self, name):
self.habits.append({
"id": str(int(time.time() * 1000)),
"name": name,
"history": {},
})
self.save()
def delete(self, idx):
if 0 <= idx < len(self.habits):
self.habits.pop(idx)
self.save()
def rename(self, idx, name):
if 0 <= idx < len(self.habits) and name:
self.habits[idx]["name"] = name
self.save()
def toggle_today(self, idx):
if not (0 <= idx < len(self.habits)):
return
hist = self.habits[idx]["history"]
t = self.today()
if hist.get(t):
hist.pop(t, None)
else:
hist[t] = True
self.save()
@staticmethod
def done_on(habit, date_str):
return bool(habit["history"].get(date_str))
def streak(self, habit):
"""Consecutive days up to today (or yesterday if today not yet done)."""
hist = habit["history"]
if not hist:
return 0
today = datetime.now().date()
# Allow the streak to count from today if done, else from yesterday so an
# unchecked 'today' doesn't instantly zero a long run.
start = today if hist.get(today.strftime("%Y-%m-%d")) else today - timedelta(days=1)
count = 0
d = start
while hist.get(d.strftime("%Y-%m-%d")):
count += 1
d -= timedelta(days=1)
return count
# ==============================================================================
# AUDIO SYNTHESIS (offline noise generation)
# ==============================================================================
class AudioSynthesizer:
# Bump this when a generator changes so existing installs regenerate.
NOISE_VERSION = "2"
@staticmethod
def synthesize_all(progress_cb=None):
os.makedirs(SOUNDS_DIR, exist_ok=True)
# Regenerate the noise loops when the algorithm version changes (smoother
# pink/brown + longer loops to kill the "harsh static" loop seam).
vfile = os.path.join(SOUNDS_DIR, ".noise_version")
cur = ""
try:
with open(vfile) as f:
cur = f.read().strip()
except OSError:
pass
if cur != AudioSynthesizer.NOISE_VERSION:
for old in ("white.wav", "pink.wav", "brown.wav"):
try:
os.unlink(os.path.join(SOUNDS_DIR, old))
except OSError:
pass
jobs = [
("white.wav", AudioSynthesizer._white, "Synthesizing white noise…"),
("pink.wav", AudioSynthesizer._pink, "Synthesizing pink noise…"),
("brown.wav", AudioSynthesizer._brown, "Synthesizing brownian noise…"),
("storm.wav", AudioSynthesizer._storm, "Synthesizing thunderstorm…"),
("alpha.wav", AudioSynthesizer._alpha, "Synthesizing alpha waves…"),
("rain.wav", AudioSynthesizer._rain, "Synthesizing rain ambience…"),
]
for i, (fname, gen, desc) in enumerate(jobs):
path = os.path.join(SOUNDS_DIR, fname)
if not os.path.exists(path):
if progress_cb:
progress_cb(desc, int(i / len(jobs) * 100))
gen(path)
try:
with open(vfile, "w") as f:
f.write(AudioSynthesizer.NOISE_VERSION)
except OSError:
pass
if progress_cb:
progress_cb("Ready!", 100)
@staticmethod
def _write_samples(filepath, gen_fn, duration=10, sr=44100):
n = duration * sr
with wave.open(filepath, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sr)
buf = []
for sample in gen_fn(n):
buf.append(struct.pack("<h", sample))
if len(buf) >= 4096:
w.writeframes(b"".join(buf))
buf = []
if buf:
w.writeframes(b"".join(buf))
@staticmethod
def _white(path):
# Gentle 1-pole low-pass softens the harshest top end (less piercing
# "hiss") while staying broadband. 20s loop reduces the audible seam.
def gen(n):
lp = 0.0
for _ in range(n):
wn = random.uniform(-1, 1)
lp = lp * 0.18 + wn * 0.82
yield int(max(-1, min(1, lp)) * 32767 * 0.55)
AudioSynthesizer._write_samples(path, gen, duration=20)
@staticmethod
def _pink(path):
# Voss-McCartney pink noise, lightly smoothed for a softer texture.
def gen(n):
rows = [0.0] * 12
rs = 0.0
lp = 0.0
for i in range(n):
if i > 0:
tz = (i & -i).bit_length() - 1
if tz < 12:
rs -= rows[tz]
rows[tz] = random.uniform(-1, 1) / 12
rs += rows[tz]
w = random.uniform(-1, 1) / 12
lp = lp * 0.35 + (rs + w) * 0.65
yield int(max(-1, min(1, lp)) * 32767 * 0.72)
AudioSynthesizer._write_samples(path, gen, duration=20)
@staticmethod
def _brown(path):
# Deeper, softer brownian rumble: stronger integration + low-pass so it
# reads as a warm "waterfall", not bright static.
def gen(n):
c = 0.0
lp = 0.0
for _ in range(n):
c += random.uniform(-1, 1) * 0.05
c *= 0.985
lp = lp * 0.55 + c * 0.45
yield int(max(-1, min(1, lp * 1.6)) * 32767 * 0.62)
AudioSynthesizer._write_samples(path, gen, duration=20)
@staticmethod
def _storm(path):
"""Enhanced thunderstorm: layered rain, deep rolling thunder, wind gusts."""
def gen(n):
sr = 44100
# Pink noise state for rain
rows = [0.0] * 16
rs = 0.0
# Brown noise for low rumble
brown = 0.0
# Thunder envelope
thunder_env = 0.0
thunder_decay = 0.99985 # Slower decay for rolling thunder
# Wind
wind_phase = 0.0
wind_speed = random.uniform(0.3, 0.7)
for i in range(n):
t = i / sr
# Pink noise rain layer
if i > 0:
tz = (i & -i).bit_length() - 1
if tz < 16:
rs -= rows[tz]
rows[tz] = random.uniform(-1, 1) / 16
rs += rows[tz]
w = random.uniform(-1, 1) / 16
rain = max(-1, min(1, rs + w))
# Shape rain with subtle high-freq emphasis
rain_shaped = rain * 0.70
# Deep brownian rumble
brown += random.uniform(-1, 1) * 0.04
brown *= 0.997
rumble = max(-1, min(1, brown)) * 0.30
# Wind gusts (slow modulation)
wind_phase += wind_speed / sr
wind_mod = (math.sin(2 * math.pi * 0.08 * t) * 0.5 + 0.5)
wind_mod *= (math.sin(2 * math.pi * 0.03 * t + 1.7) * 0.3 + 0.7)
wind = random.uniform(-1, 1) * wind_mod * 0.15
# Thunder strikes — less frequent but more dramatic
if random.random() < 0.000008:
thunder_env = random.uniform(0.8, 1.0)
clap = 0.0
if thunder_env > 0.0005:
# Multi-layered thunder: crack + rumble
crack = random.uniform(-1, 1) * thunder_env * 0.5
low_rumble = math.sin(2 * math.pi * (30 + random.uniform(-5, 5)) * t) * thunder_env * 0.3
clap = crack + low_rumble
thunder_env *= thunder_decay
sample = rain_shaped + rumble + wind + clap
yield int(max(-1, min(1, sample)) * 32767 * 0.85)
AudioSynthesizer._write_samples(path, gen, duration=15)
@staticmethod
def _rain(path):
"""Pure rain ambience — gentle steady rainfall."""
def gen(n):
rows = [0.0] * 14
rs = 0.0
for i in range(n):
if i > 0:
tz = (i & -i).bit_length() - 1
if tz < 14:
rs -= rows[tz]
rows[tz] = random.uniform(-1, 1) / 14
rs += rows[tz]
w = random.uniform(-1, 1) / 14
rain = max(-1, min(1, rs + w)) * 0.80
# Add occasional drip droplets
drip = 0.0
if random.random() < 0.0002:
drip = math.sin(2 * math.pi * random.uniform(2000, 5000) * i / 44100) * 0.25
yield int(max(-1, min(1, rain + drip)) * 32767 * 0.80)
AudioSynthesizer._write_samples(path, gen)
@staticmethod
def _alpha(path):
def gen(n):
sr = 44100
c = 0.0
for i in range(n):
t = i / sr
beat = (math.sin(2 * math.pi * 100 * t) + math.sin(2 * math.pi * 110 * t)) * 0.5
c += random.uniform(-1, 1) * 0.03
c *= 0.995
rumble = max(-1, min(1, c)) * 0.15
val = beat * 0.5 + rumble * 0.5
yield int(max(-1, min(1, val)) * 32767 * 0.80)
AudioSynthesizer._write_samples(path, gen)
# ==============================================================================
# AMBIENT RECORDINGS — real CC0/public-domain sounds, downloaded on first run
# ==============================================================================
# Verified reachable 2026-06-13. key -> (url, local filename)
SOUND_DOWNLOADS = {
# Pure rain, no thunder (1m22s loop) — fixes the "rain has thunder" report.
"rain": ("https://upload.wikimedia.org/wikipedia/commons/4/41/Rain_against_the_window.ogg", "rain_window.ogg"),
"thunder": ("https://upload.wikimedia.org/wikipedia/commons/b/b1/Thunderstorm_after_hot_summer_day_17_minutes_02_of_04.ogg", "thunder.ogg"),
# Sea waves with clear swell — distinct from the forest-wind recording.
"ocean": ("https://upload.wikimedia.org/wikipedia/commons/e/e9/Adriatic_Sea_waves.ogg", "ocean_waves.ogg"),
"fireplace": ("https://archive.org/download/ronkoster2023-fireplace-with-crackling-sounds-2-min-rk-178392/ronkoster2023-fireplace-with-crackling-sounds-2-min-rk-178392.mp3", "fireplace.mp3"),
"birds": ("https://upload.wikimedia.org/wikipedia/commons/e/e7/Birdsong_morning_01.ogg", "birds.ogg"),
"cafe": ("https://archive.org/download/453074-c-rogers-370973-waweee-coffee-shop-ambience-remastered/453074__c_rogers__370973__waweee__coffee-shop-ambience_remastered.mp3", "cafe.mp3"),
"wind": ("https://upload.wikimedia.org/wikipedia/commons/f/f3/Wind_in_Swedish_pine_forest_at_25_mps.ogg", "wind.ogg"),
}
def _install_krishna_flute():
"""Copy the Krishna flute MP3 bundled next to this script into SOUNDS_DIR."""
dest = os.path.join(SOUNDS_DIR, "krishna_flute.mp3")
if os.path.exists(dest) and os.path.getsize(dest) > 1024:
return
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
for cand in os.listdir(script_dir):
if cand.lower().endswith(".mp3") and "krishna" in cand.lower():
shutil.copyfile(os.path.join(script_dir, cand), dest)
return
except Exception:
pass
def download_sounds(progress_cb=None):
"""Fetch real recordings on first run. Missing files are left missing so the
AudioEngine can fall back to a synthesized WAV (never silent)."""
os.makedirs(SOUNDS_DIR, exist_ok=True)
_install_krishna_flute()
items = list(SOUND_DOWNLOADS.items())
for i, (key, (url, fname)) in enumerate(items):
dest = os.path.join(SOUNDS_DIR, fname)
if os.path.exists(dest) and os.path.getsize(dest) > 1024:
continue
tmp = dest + ".part"
# Retry: archive.org download nodes can be slow to warm up on a cold
# request (occasionally >30s the first time, fast after). 3 tries.
for attempt in range(3):
if progress_cb:
suffix = "…" if attempt == 0 else f" (retry {attempt})…"
progress_cb(f"Downloading {key}{suffix}", int(i / max(1, len(items)) * 100))
try:
req = urllib.request.Request(url, headers={"User-Agent": "flow-tui/1.0"})
with urllib.request.urlopen(req, timeout=60) as r, open(tmp, "wb") as f:
while True:
chunk = r.read(65536)
if not chunk:
break
f.write(chunk)
os.replace(tmp, dest)
break # success
except Exception:
try:
os.unlink(tmp)
except OSError:
pass
time.sleep(1.5)
# after final attempt: leave missing → falls back to synth/None
# ==============================================================================
# AUDIO ENGINE — mpv via JSON IPC socket (reliable)
# ==============================================================================
class AudioEngine:
def __init__(self, config):
self.config = config
self.mpv_proc = None
self.current_sound_idx = 0
self.volume = 50
self.is_playing = False
self._lock = threading.Lock() # serialize IPC across UI + watchdog threads
self._watchdog_on = True
self.sounds = [
{"name": "None", "type": "none", "files": []},
{"name": "🌧 Rain", "type": "local", "files": ["rain_window.ogg", "rain.ogg", "rain.wav"]},
{"name": "⛈ Thunderstorm", "type": "local", "files": ["thunder.ogg", "storm.wav"]},
{"name": "🌊 Ocean Waves", "type": "local", "files": ["ocean_waves.ogg", "ocean.mp3", "ocean.wav"]},
{"name": "🔥 Fireplace", "type": "local", "files": ["fireplace.mp3", "fire.wav"]},
{"name": "🐦 Birds", "type": "local", "files": ["birds.ogg", "birds.wav"]},
{"name": "☕ Café", "type": "local", "files": ["cafe.mp3", "cafe.wav"]},
{"name": "💨 Wind", "type": "local", "files": ["wind.ogg", "wind.wav"]},
{"name": "🎵 Krishna Flute","type": "local", "files": ["krishna_flute.mp3"]},
{"name": "〰 Alpha Waves", "type": "local", "files": ["alpha.wav"]},
{"name": "White Noise", "type": "local", "files": ["white.wav"]},
{"name": "Pink Noise", "type": "local", "files": ["pink.wav"]},
{"name": "Brown Noise", "type": "local", "files": ["brown.wav"]},
{"name": "📻 Lofi Radio", "type": "stream", "path": "http://stream.zeno.fm/0r0xa792kwzuv"},
]
# Multi-sound mixer: one mpv process per active sound, keyed by sound idx.
self.instances = {} # idx -> {"proc": Popen, "sock": path, "type": str}
self.muted = False
# Watchdog reconnects dropped network streams so playback never dies.
self._watchdog_thread = threading.Thread(target=self._watchdog, daemon=True)
self._watchdog_thread.start()
def resolve_path(self, sound):
"""Return the first existing file for a sound, or None if unavailable."""
if sound.get("type") == "stream":
return sound.get("path")
for fn in sound.get("files", []):
p = os.path.join(SOUNDS_DIR, fn)
if os.path.exists(p):
return p
return None
def _sock_path(self, idx):
return f"{MPV_SOCKET}_{idx}"
def _spawn_mpv(self, sock):
try:
os.unlink(sock)
except OSError:
pass
try:
proc = subprocess.Popen(
["mpv", "--idle", "--quiet", "--no-video",
f"--input-ipc-server={sock}",
"--cache=yes", "--cache-secs=60",
"--demuxer-readahead-secs=60",
"--demuxer-max-bytes=64MiB",
"--demuxer-max-back-bytes=32MiB",
"--network-timeout=0",
"--stream-lavf-o-append=reconnect=1",
"--stream-lavf-o-append=reconnect_streamed=1",
"--stream-lavf-o-append=reconnect_on_network_error=1",
"--stream-lavf-o-append=reconnect_delay_max=60"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
except Exception:
return None
for _ in range(30):
if os.path.exists(sock):
break
time.sleep(0.05)
return proc
def _cmd_sock(self, sock, *args):
try:
with self._lock:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(0.5)
s.connect(sock)
s.sendall((json.dumps({"command": list(args)}) + "\n").encode())
s.close()
except Exception:
pass
def _get_sock(self, sock, prop):
try:
with self._lock:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(0.5)
s.connect(sock)
s.sendall((json.dumps({"command": ["get_property", prop]}) + "\n").encode())
buf = b""
while b"\n" not in buf:
chunk = s.recv(4096)
if not chunk:
break
buf += chunk
s.close()
for line in buf.split(b"\n"):
if not line.strip():
continue
msg = json.loads(line.decode())
if msg.get("error") == "success" and "data" in msg:
return msg["data"]
except Exception:
return None
return None
def _start_instance(self, idx):
"""Spawn an mpv for sound idx and begin looping it. Returns True on success."""
sound = self.sounds[idx]
path = self.resolve_path(sound)
if not path:
return False
sock = self._sock_path(idx)
proc = self._spawn_mpv(sock)
if not proc:
return False
self._cmd_sock(sock, "loadfile", path, "replace")
time.sleep(0.05)
self._cmd_sock(sock, "set_property", "loop-file", "inf")
time.sleep(0.02)
self._cmd_sock(sock, "set_property", "volume", 0 if self.muted else self.volume)
self._cmd_sock(sock, "set_property", "pause", False)
self.instances[idx] = {"proc": proc, "sock": sock, "type": sound["type"]}
return True
def _stop_instance(self, idx):
inst = self.instances.pop(idx, None)
if not inst:
return
try:
inst["proc"].terminate()
inst["proc"].wait(timeout=1)
except Exception:
try:
inst["proc"].kill()
except Exception:
pass
try:
os.unlink(inst["sock"])
except OSError:
pass
def _refresh_state(self):
self.is_playing = bool(self.instances) and not self.muted
if self.instances:
if self.current_sound_idx not in self.instances:
self.current_sound_idx = sorted(self.instances)[0]
else:
self.current_sound_idx = 0
def toggle_sound(self, idx):
"""Add/remove a sound from the simultaneous mix (mouse + Enter entry point)."""
if idx == 0: # the "None" row clears the whole mix
self.stop()
return
if not self.config.sound_enabled:
return
if idx in self.instances:
self._stop_instance(idx)
else:
if self._start_instance(idx):
self.current_sound_idx = idx
self.muted = False
self._refresh_state()
# Back-compat alias — older call sites (and the watchdog) used play().
def play(self, idx):
self.toggle_sound(idx)
def is_active(self, idx):
return idx in self.instances and not self.muted
def active_count(self):
return len(self.instances)
def status_label(self):
"""Short 'now playing' label for the home/timer footer."""
if not self.instances:
return ""
names = [self.sounds[i]["name"] for i in sorted(self.instances)]
head = names[0]
extra = len(names) - 1
return head + (f" +{extra}" if extra else "")
def stop(self):
for idx in list(self.instances):
self._stop_instance(idx)
self.is_playing = False
self.current_sound_idx = 0
def toggle(self):
"""Mute/unmute the whole mix (keeps the selection)."""
if not self.instances:
return
self.muted = not self.muted
vol = 0 if self.muted else self.volume
for inst in self.instances.values():
self._cmd_sock(inst["sock"], "set_property", "volume", vol)
self.is_playing = bool(self.instances) and not self.muted
def set_volume(self, vol):
self.volume = max(0, min(100, vol))
if not self.muted:
for inst in self.instances.values():
self._cmd_sock(inst["sock"], "set_property", "volume", self.volume)
def _watchdog(self):
"""Reload any network-stream instance that drops while we expect playback."""
while self._watchdog_on:
time.sleep(2.0)
try:
for idx, inst in list(self.instances.items()):
if inst["type"] != "stream":
continue
sock = inst["sock"]
if (inst["proc"].poll() is not None
or self._get_sock(sock, "eof-reached") is True
or self._get_sock(sock, "idle-active") is True):
self._stop_instance(idx)
self._start_instance(idx)
except Exception:
pass
def one_shot(self, name):
if not self.config.sound_enabled:
return
paths = {
"work": "/usr/share/sounds/freedesktop/stereo/complete.oga",
"break": "/usr/share/sounds/freedesktop/stereo/bell.oga",
"alarm": "/usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga",
}
p = paths.get(name)
if p and os.path.exists(p):
subprocess.Popen(
["paplay", p],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
else:
sys.stdout.write("\a")
sys.stdout.flush()
def shutdown(self):
self._watchdog_on = False
self.stop() # terminates every per-sound mpv + unlinks its socket
# ==============================================================================
# BLOCKER ENGINE — kills blocked apps during focus, allows during break
# ==============================================================================
_PKG_NOISE = {"bin", "git", "debug", "stable", "real", "app", "appimage", "flatpak"}
def name_tokens(s):
"""Split a name/path into lowercase alphanumeric tokens, dropping packaging
noise. Splits on ANY non-alphanumeric (incl. '/' in cmdline paths) so a
blocked 'google-chrome' matches the cmdline '/opt/google/chrome/chrome'."""
toks = set(re.split(r"[^a-z0-9]+", s.lower()))
toks.discard("")
return toks - _PKG_NOISE
def clean_proc_name(name):
"""Back-compat: a normalized display string (space-joined significant tokens)."""
return " ".join(sorted(name_tokens(name)))
class BlockerEngine:
def __init__(self, config):
self.config = config
self.running = False
self.is_break = False # set by timer to allow apps during break
self.thread = None
self.my_pid = os.getpid()
def start(self, is_break=False):
self.is_break = is_break