-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_tracker.py
More file actions
1921 lines (1685 loc) · 94.8 KB
/
Copy pathgui_tracker.py
File metadata and controls
1921 lines (1685 loc) · 94.8 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
from __future__ import annotations
import importlib.util, os as _os
def _fix_qt_plugin_path():
spec = importlib.util.find_spec("PyQt6")
if spec and spec.origin:
p = _os.path.join(_os.path.dirname(spec.origin), "Qt6", "plugins", "platforms")
if _os.path.isdir(p):
_os.environ.setdefault("QT_QPA_PLATFORM_PLUGIN_PATH", p)
_fix_qt_plugin_path()
"""Echo Bike Tracker — macOS GUI v4
Rogue Echo Bike v3 · FTMS Bluetooth
Usage: python3 gui_tracker.py
"""
import asyncio, copy, csv, json, struct, sys, threading
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
import pyqtgraph as pg
from bleak import BleakClient, BleakScanner
from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QObject
from PyQt6.QtGui import QColor, QPalette
from PyQt6.QtWidgets import (
QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox,
QDoubleSpinBox, QFrame, QGridLayout, QHBoxLayout, QHeaderView,
QLabel, QLineEdit, QListWidget, QMainWindow, QMessageBox,
QProgressBar, QPushButton, QScrollArea, QSizePolicy, QSpinBox,
QStatusBar, QTableWidget, QTableWidgetItem, QTabWidget,
QVBoxLayout, QWidget,
)
# ─── FTMS UUIDs ───────────────────────────────────────────────────────────────
FTMS_SERVICE_UUID = "00001826-0000-1000-8000-00805f9b34fb"
INDOOR_BIKE_DATA = "00002ad2-0000-1000-8000-00805f9b34fb"
HEART_RATE_UUID = "00002a37-0000-1000-8000-00805f9b34fb"
FTMS_CONTROL_UUID = "00002ad9-0000-1000-8000-00805f9b34fb"
# Mac App Store sandbox-compatible path (also works outside the sandbox)
_APP_SUPPORT = Path.home() / "Library" / "Application Support" / "Echo Bike Tracker"
WORKOUTS_DIR = _APP_SUPPORT / "workouts"
PROFILES_FILE = WORKOUTS_DIR / "profiles.json"
PB_FILE = WORKOUTS_DIR / "personal_bests.json"
ECHO_BIKE_KEYWORDS = {"rogue", "echo", "bike", "assault"}
MAX_CHART_POINTS = 1800
# ─── Colours ──────────────────────────────────────────────────────────────────
BG = "#0d0d1a"
CARD_BG = "#14142a"
CARD_BORDER = "#252545"
COL_POWER = "#ff6b35"
COL_WKG = "#fd79a8"
COL_CADENCE = "#00d4ff"
COL_SPEED = "#00e676"
COL_HR = "#ff4757"
COL_CALS = "#ffd32a"
COL_DIST = "#a29bfe"
COL_TIME = "#dfe6e9"
COL_MUTED = "#6c6c9a"
COL_WHITE = "#ffffff"
COL_WORK = "#ff6b35"
COL_REST = "#00d4ff"
COL_GOLD = "#ffd700"
COL_SUCCESS = "#00e676"
# ─── Training zones ───────────────────────────────────────────────────────────
# Power zones: (min_pct_ftp, max_pct_ftp, label, colour)
POWER_ZONES = [
( 0, 55, "Z1 Recovery", "#6c6c9a"),
( 55, 75, "Z2 Endurance", "#00d4ff"),
( 75, 90, "Z3 Tempo", "#00e676"),
( 90, 105, "Z4 Threshold", "#ffd32a"),
(105, 120, "Z5 VO2 Max", "#ff6b35"),
(120, 150, "Z6 Anaerobic", "#fd79a8"),
(150, 999, "Z7 Sprint", "#ff4757"),
]
# HR zones: HRR % (Karvonen)
HR_ZONES = [
( 0, 50, "Z1 Rest", "#6c6c9a"),
( 50, 60, "Z2 Easy", "#00d4ff"),
( 60, 70, "Z3 Aerobic", "#00e676"),
( 70, 80, "Z4 Threshold", "#ffd32a"),
( 80, 90, "Z5 Hard", "#ff6b35"),
( 90, 200, "Z6 Max", "#ff4757"),
]
def get_power_zone(watts: int, ftp: int) -> tuple[int, str, str]:
if ftp <= 0:
return 0, "", COL_MUTED
pct = watts / ftp * 100
for i, (lo, hi, name, col) in enumerate(POWER_ZONES):
if pct < hi:
return i, name, col
return len(POWER_ZONES)-1, POWER_ZONES[-1][2], POWER_ZONES[-1][3]
def get_hr_zone(hr: int, resting: int, max_hr: int) -> tuple[int, str, str]:
hrr = max_hr - resting
if hrr <= 0:
return 0, "", COL_MUTED
pct = max(0.0, (hr - resting) / hrr * 100)
for i, (lo, hi, name, col) in enumerate(HR_ZONES):
if pct < hi:
return i, name, col
return len(HR_ZONES)-1, HR_ZONES[-1][2], HR_ZONES[-1][3]
def vo2max_from_ftp(ftp_w: float, weight_kg: float) -> float:
"""Hawley & Noakes via Coggan: MAP = FTP/0.76; VO2max = (MAP×10.8/weight)+7"""
if weight_kg <= 0 or ftp_w <= 0: return 0.0
map_w = ftp_w / 0.76
return round((map_w * 10.8 / weight_kg) + 7, 1)
def vo2max_from_hr(max_hr: int, resting_hr: int) -> float:
"""Uth–Sørensen formula: VO2max ≈ 15 × (HRmax / HRrest)"""
if resting_hr <= 0 or max_hr <= 0: return 0.0
return round(15 * max_hr / resting_hr, 1)
def vo2max_classification(v: float) -> tuple[str, str]:
"""Returns (label, colour) for a VO2max value."""
for lo, hi, label, col in [
(0, 30, "Poor", "#ff4757"),
(30, 38, "Below average", "#fd79a8"),
(38, 46, "Average", "#ffd32a"),
(46, 54, "Good", "#00e676"),
(54, 62, "Very good", "#00d4ff"),
(62, 999,"Excellent", "#a29bfe"),
]:
if v < hi:
return label, col
return "Excellent", "#a29bfe"
# ─── Rider profiles ───────────────────────────────────────────────────────────
RIDER_NAMES = ["Clare", "Richie", "Ross", "Guest"]
DEFAULT_PROFILES: dict[str, dict] = {
"Clare": {"weight_kg": 65.0, "age": 35, "resting_hr": 55, "ftp_w": 180, "max_hr_override": 0},
"Richie": {"weight_kg": 80.0, "age": 38, "resting_hr": 52, "ftp_w": 220, "max_hr_override": 0},
"Ross": {"weight_kg": 75.0, "age": 35, "resting_hr": 58, "ftp_w": 200, "max_hr_override": 0},
"Guest": {"weight_kg": 75.0, "age": 30, "resting_hr": 60, "ftp_w": 200, "max_hr_override": 0},
}
def _profile_max_hr(p: dict) -> int:
override = p.get("max_hr_override", 0)
return override if override > 0 else 220 - p.get("age", 30)
def load_profiles() -> dict:
base = {k: dict(v) for k, v in DEFAULT_PROFILES.items()}
if PROFILES_FILE.exists():
try:
saved = json.loads(PROFILES_FILE.read_text())
for name, data in saved.items():
if name in base:
base[name].update(data)
else:
base[name] = data
except Exception:
pass
return base
def save_profiles(profiles: dict):
WORKOUTS_DIR.mkdir(parents=True, exist_ok=True)
PROFILES_FILE.write_text(json.dumps(profiles, indent=2))
def load_pbs() -> dict:
if PB_FILE.exists():
try:
return json.loads(PB_FILE.read_text())
except Exception:
pass
return {}
def save_pbs(pbs: dict):
WORKOUTS_DIR.mkdir(parents=True, exist_ok=True)
PB_FILE.write_text(json.dumps(pbs, indent=2))
def update_pbs(rider: str, summary: dict) -> dict[str, bool]:
"""Update PBs for rider; returns {field: True} for new records."""
if not rider:
return {}
pbs = load_pbs()
rpb = pbs.get(rider, {})
new: dict[str, bool] = {}
def chk(key, val):
if val is None: return
if rpb.get(key) is None or val > rpb[key]:
rpb[key] = val
new[key] = True
dur = summary.get("duration_seconds") or 0
dist = (summary.get("distance_m") or 0) / 1000
cals = summary.get("total_calories") or 0
rpb["total_time_s"] = rpb.get("total_time_s", 0) + dur
rpb["total_distance_km"] = round(rpb.get("total_distance_km", 0) + dist, 3)
rpb["total_calories"] = rpb.get("total_calories", 0) + int(cals)
rpb["workout_count"] = rpb.get("workout_count", 0) + 1
chk("max_power_w", summary.get("max_power_w"))
chk("best_avg_power", summary.get("avg_power_w"))
chk("best_avg_wkg", summary.get("avg_wkg"))
chk("max_hr", summary.get("max_hr"))
chk("max_cadence_rpm", summary.get("max_cadence_rpm"))
pbs[rider] = rpb
save_pbs(pbs)
return new
# ─── FTMS parser ──────────────────────────────────────────────────────────────
def parse_indoor_bike_data(raw: bytes) -> dict:
if len(raw) < 2: return {}
result: dict = {}
off = 0
flags = struct.unpack_from("<H", raw, off)[0]; off += 2
def rd(fmt):
nonlocal off
n = struct.calcsize(fmt)
if off + n > len(raw): return None
v = struct.unpack_from(fmt, raw, off)[0]; off += n; return v
if not (flags & 0x0001):
v = rd("<H"); result["speed_kmh"] = round(v*0.01, 2) if v is not None else None
if flags & 0x0002:
v = rd("<H"); result["avg_speed_kmh"] = round(v*0.01, 2) if v is not None else None
if flags & 0x0004:
v = rd("<H"); result["cadence_rpm"] = round(v*0.5, 1) if v is not None else None
if flags & 0x0008:
v = rd("<H"); result["avg_cadence_rpm"] = round(v*0.5, 1) if v is not None else None
if flags & 0x0010:
if off+3 <= len(raw):
result["distance_m"] = struct.unpack_from("<I", raw[off:off+3]+b"\x00")[0]; off += 3
if flags & 0x0020:
v = rd("<h"); result["resistance"] = v
if flags & 0x0040:
v = rd("<h"); result["power_w"] = v
if flags & 0x0080:
v = rd("<h"); result["avg_power_w"] = v
if flags & 0x0100:
t = rd("<H"); h = rd("<H"); m = rd("<B")
if t is not None: result["calories"] = t
if h is not None: result["calories_per_hour"] = h
if m is not None: result["calories_per_minute"] = m
if flags & 0x0200:
v = rd("<B"); result["heart_rate"] = v
if flags & 0x0400: rd("<B")
if flags & 0x0800:
v = rd("<H"); result["elapsed_seconds"] = v
if flags & 0x1000:
v = rd("<H"); result["remaining_seconds"] = v
return {k: v for k, v in result.items() if v is not None}
def parse_heart_rate(raw: bytes) -> int | None:
if not raw: return None
return struct.unpack_from("<H", raw, 1)[0] if (raw[0] & 0x01) and len(raw) >= 3 \
else (raw[1] if len(raw) >= 2 else None)
# ─── Segment model ────────────────────────────────────────────────────────────
@dataclass
class Segment:
name: str
duration_s: int
target_type: str # "Open"|"Power"|"HR"|"Cadence"
target_value: int = 0
@property
def duration_str(self) -> str:
m, s = divmod(self.duration_s, 60); return f"{m:02d}:{s:02d}"
@property
def target_str(self) -> str:
u = {"Power": "W", "HR": "bpm", "Cadence": "rpm"}
return "Open" if self.target_type == "Open" \
else f"{self.target_value} {u.get(self.target_type,'')}"
@property
def color(self) -> str:
return {"Warmup": COL_MUTED, "Cooldown": COL_MUTED,
"Work": COL_WORK, "Sprint": COL_WORK,
"Rest": COL_REST, "Recovery": COL_REST,
}.get(self.name, COL_WHITE)
SEGMENT_NAMES = ["Warmup","Work","Sprint","Steady","Rest","Recovery","Cooldown","Custom"]
WORKOUT_TEMPLATES: dict[str, list[Segment]] = {
"Tabata (20s/10s × 8)": [
Segment("Warmup", 300, "Open"),
*([Segment("Work", 20, "Power", 250), Segment("Rest", 10, "Power", 80)] * 8),
Segment("Cooldown", 300, "Open"),
],
"30/30 Intervals × 10": [
Segment("Warmup", 300, "Open"),
*([Segment("Work", 30, "Power", 200), Segment("Rest", 30, "Power", 80)] * 10),
Segment("Cooldown", 300, "Open"),
],
"40/20 Intervals × 8": [
Segment("Warmup", 300, "Open"),
*([Segment("Work", 40, "Power", 220), Segment("Rest", 20, "Power", 80)] * 8),
Segment("Cooldown", 300, "Open"),
],
"Steady State 20 min": [
Segment("Warmup", 300, "Open"),
Segment("Steady", 1200, "Power", 150),
Segment("Cooldown", 300, "Open"),
],
"Zone 2 45 min Easy": [
Segment("Warmup", 300, "Open"),
Segment("Steady", 2700, "Power", 130),
Segment("Cooldown", 300, "Open"),
],
"10-20-30 × 5 rounds": [
Segment("Warmup", 300, "Open"),
*([Segment("Easy", 30, "Power", 100),
Segment("Moderate", 20, "Power", 180),
Segment("Sprint", 10, "Power", 350)] * 5),
Segment("Cooldown", 300, "Open"),
],
"Pyramid (1-2-3-2-1 min)": [
Segment("Warmup", 300, "Open"),
Segment("Work", 60, "Power", 230), Segment("Rest", 60, "Power", 80),
Segment("Work", 120, "Power", 210), Segment("Rest", 60, "Power", 80),
Segment("Work", 180, "Power", 190), Segment("Rest", 90, "Power", 80),
Segment("Work", 120, "Power", 210), Segment("Rest", 60, "Power", 80),
Segment("Work", 60, "Power", 230),
Segment("Cooldown", 300, "Open"),
],
"EMOM (40s work / 20s rest × 12)": [
Segment("Warmup", 300, "Open"),
*([Segment("Work", 40, "Power", 200), Segment("Rest", 20, "Power", 70)] * 12),
Segment("Cooldown", 300, "Open"),
],
"4×8 min Threshold": [
Segment("Warmup", 600, "Open"),
*([Segment("Work", 480, "Power", 200), Segment("Rest", 240, "Power", 80)] * 4),
Segment("Cooldown", 600, "Open"),
],
"6×1 min VO2 Max": [
Segment("Warmup", 600, "Open"),
*([Segment("Sprint", 60, "Power", 280), Segment("Rest", 120, "Power", 70)] * 6),
Segment("Cooldown", 600, "Open"),
],
"Sprint Repeats 8×20s": [
Segment("Warmup", 300, "Open"),
*([Segment("Sprint", 20, "Power", 400), Segment("Rest", 40, "Power", 60)] * 8),
Segment("Cooldown", 300, "Open"),
],
"5×5 min Tempo": [
Segment("Warmup", 600, "Open"),
*([Segment("Work", 300, "Power", 185), Segment("Rest", 60, "Power", 80)] * 5),
Segment("Cooldown", 600, "Open"),
],
"FTP Test (20 min all-out)": [
Segment("Warmup", 600, "Open"),
Segment("Easy", 300, "Power", 100),
Segment("Sprint", 30, "Power", 300),
Segment("Rest", 300, "Open"),
Segment("TEST", 1200, "Open"),
Segment("Cooldown", 600, "Open"),
],
"Ramp Test (1 min steps)": [
Segment("Warmup", 300, "Power", 80),
*[Segment(f"Step {i+1}", 60, "Power", 100 + i*20) for i in range(13)],
Segment("Cooldown", 300, "Open"),
],
}
# ─── BLE worker ───────────────────────────────────────────────────────────────
class BleWorker(QObject):
data_received = pyqtSignal(dict)
connected = pyqtSignal(str)
disconnected = pyqtSignal()
error = pyqtSignal(str)
scan_result = pyqtSignal(list)
control_sent = pyqtSignal(str)
def __init__(self):
super().__init__()
self._loop: asyncio.AbstractEventLoop | None = None
self._client: BleakClient | None = None
def start(self): threading.Thread(target=self._run_loop, daemon=True).start()
def _run_loop(self):
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._loop.run_forever()
def _go(self, coro):
if self._loop: asyncio.run_coroutine_threadsafe(coro, self._loop)
def scan(self): self._go(self._scan())
def connect_to(self, addr: str): self._go(self._connect(addr))
def disconnect(self): self._go(self._disconnect())
async def _scan(self):
try:
devs = await BleakScanner.discover(timeout=10.0, service_uuids=[FTMS_SERVICE_UUID])
if not devs:
all_d = await BleakScanner.discover(timeout=8.0)
devs = [d for d in all_d
if d.name and any(k in d.name.lower() for k in ECHO_BIKE_KEYWORDS)]
self.scan_result.emit([(d.name or "Unknown", d.address) for d in devs])
except Exception as e: self.error.emit(str(e))
async def _connect(self, addr: str):
try:
self._client = BleakClient(
addr, timeout=20.0,
disconnected_callback=lambda _: self.disconnected.emit(),
)
await self._client.connect()
self.connected.emit(addr)
await self._client.start_notify(INDOOR_BIKE_DATA, self._on_bike)
try: await self._client.start_notify(HEART_RATE_UUID, self._on_hr)
except Exception: pass
except Exception as e: self.error.emit(str(e))
async def _disconnect(self):
if self._client and self._client.is_connected:
try: await self._client.stop_notify(INDOOR_BIKE_DATA)
except Exception: pass
await self._client.disconnect()
def _on_bike(self, _s, raw: bytes):
parsed = parse_indoor_bike_data(bytes(raw))
if parsed: parsed["ts"] = datetime.now().isoformat(); self.data_received.emit(parsed)
def _on_hr(self, _s, raw: bytes):
hr = parse_heart_rate(bytes(raw))
if hr is not None: self.data_received.emit({"heart_rate": hr, "ts": datetime.now().isoformat()})
def request_control(self): self._go(self._ctrl_write(bytes([0x00]), "Request Control"))
def send_target_power(self, w): self._go(self._ctrl_write(bytes([0x05, w&0xFF, (w>>8)&0xFF]), f"Power→{w}W"))
def send_target_hr(self, b): self._go(self._ctrl_write(bytes([0x06, max(0,min(b,255))]), f"HR→{b}bpm"))
def send_target_cadence(self, r): self._go(self._ctrl_write(bytes([0x14, r&0xFF, (r>>8)&0xFF]), f"Cadence→{r}rpm"))
def ftms_start(self): self._go(self._ctrl_write(bytes([0x07]), "Start"))
def ftms_stop(self): self._go(self._ctrl_write(bytes([0x08, 0x01]), "Stop"))
async def _ctrl_write(self, data: bytes, desc: str):
if not (self._client and self._client.is_connected): return
try:
await self._client.write_gatt_char(FTMS_CONTROL_UUID, data, response=True)
self.control_sent.emit(desc)
except Exception: pass
# ─── Metric card ──────────────────────────────────────────────────────────────
class MetricCard(QFrame):
def __init__(self, label: str, unit: str, color: str,
big: bool = False, show_zone: bool = False, show_stats: bool = False):
super().__init__()
self._color = color
self._has_zone = show_zone
self._has_stats = show_stats
self.setStyleSheet(
f"MetricCard{{background:{CARD_BG};border:1px solid {CARD_BORDER};border-radius:14px;}}"
)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumSize(110, 110)
lay = QVBoxLayout(self)
lay.setContentsMargins(10, 8, 10, 8)
lay.setSpacing(1)
lbl = QLabel(label)
lbl.setStyleSheet(
f"color:{COL_MUTED};font-size:10px;font-weight:700;"
f"letter-spacing:1.5px;border:none;background:transparent;"
)
lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
lay.addWidget(lbl)
lay.addStretch(1)
fs = 40 if big else 34
self._val = QLabel("--")
self._val.setStyleSheet(
f"color:{color};font-size:{fs}px;font-weight:800;"
f"border:none;background:transparent;"
)
self._val.setAlignment(Qt.AlignmentFlag.AlignCenter)
lay.addWidget(self._val)
unit_lbl = QLabel(unit)
unit_lbl.setStyleSheet(f"color:{COL_MUTED};font-size:11px;border:none;background:transparent;")
unit_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
lay.addWidget(unit_lbl)
lay.addStretch(1)
if show_zone:
self._zone_lbl = QLabel("")
self._zone_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._zone_lbl.setStyleSheet(
f"color:{COL_MUTED};font-size:9px;font-weight:700;"
f"letter-spacing:0.5px;border:none;background:transparent;"
)
lay.addWidget(self._zone_lbl)
if show_stats:
sr = QHBoxLayout(); sr.setSpacing(0)
self._min_lbl = QLabel("↓--")
self._avg_lbl = QLabel("~--")
self._max_lbl = QLabel("↑--")
for l in (self._min_lbl, self._avg_lbl, self._max_lbl):
l.setStyleSheet(
f"color:{COL_MUTED};font-size:9px;border:none;background:transparent;"
)
l.setAlignment(Qt.AlignmentFlag.AlignCenter)
sr.addWidget(l)
lay.addLayout(sr)
def set_value(self, v, decimals: int = 0):
if isinstance(v, (int, float)):
self._val.setText(f"{v:.{decimals}f}" if decimals else f"{v:.0f}")
else:
self._val.setText(str(v))
def set_zone(self, name: str, color: str):
if self._has_zone:
self._zone_lbl.setText(name)
self._zone_lbl.setStyleSheet(
f"color:{color};font-size:9px;font-weight:700;"
f"letter-spacing:0.5px;border:none;background:transparent;"
)
def set_stats(self, mn, avg, mx, fmt="{:.0f}"):
if not self._has_stats: return
self._min_lbl.setText(f"↓{fmt.format(mn)}" if mn is not None else "↓--")
self._avg_lbl.setText(f"~{fmt.format(avg)}" if avg is not None else "~--")
self._max_lbl.setText(f"↑{fmt.format(mx)}" if mx is not None else "↑--")
# ─── Button style ─────────────────────────────────────────────────────────────
def _btn_style(color: str, width: int | None = None) -> str:
w = f"min-width:{width}px;" if width else ""
return f"""
QPushButton {{
background:{color}20;color:{color};
border:1px solid {color}60;border-radius:9px;
font-size:13px;font-weight:700;
padding:0 18px;height:38px;{w}
}}
QPushButton:hover {{background:{color}40;}}
QPushButton:pressed {{background:{color}60;}}
QPushButton:disabled {{background:transparent;color:#3a3a5a;border-color:#2a2a4a;}}
"""
def _field_ss() -> str:
return (f"background:#0d0d1a;color:{COL_WHITE};"
f"border:1px solid {CARD_BORDER};border-radius:6px;"
f"padding:3px 8px;font-size:12px;")
# ─── Profile dialog ───────────────────────────────────────────────────────────
class ProfileDialog(QDialog):
def __init__(self, name: str, profile: dict, parent=None):
super().__init__(parent)
self.setWindowTitle(f"Profile: {name}")
self.setStyleSheet(f"background:{BG};color:{COL_WHITE};")
self.resize(360, 280)
self._result: dict | None = None
lay = QVBoxLayout(self)
lay.setSpacing(12); lay.setContentsMargins(20, 16, 20, 16)
grid = QGridLayout(); grid.setSpacing(10)
def row(label, widget, r):
lbl = QLabel(label)
lbl.setStyleSheet(f"color:{COL_MUTED};font-size:11px;font-weight:700;")
grid.addWidget(lbl, r, 0)
grid.addWidget(widget, r, 1)
self._weight = QDoubleSpinBox(); self._weight.setRange(30, 250); self._weight.setDecimals(1)
self._weight.setSuffix(" kg"); self._weight.setValue(profile.get("weight_kg", 75))
self._weight.setStyleSheet(_field_ss())
self._age = QSpinBox(); self._age.setRange(10, 90)
self._age.setValue(profile.get("age", 30)); self._age.setStyleSheet(_field_ss())
self._rest_hr = QSpinBox(); self._rest_hr.setRange(30, 120)
self._rest_hr.setSuffix(" bpm"); self._rest_hr.setValue(profile.get("resting_hr", 60))
self._rest_hr.setStyleSheet(_field_ss())
self._ftp = QSpinBox(); self._ftp.setRange(50, 2000)
self._ftp.setSuffix(" W"); self._ftp.setValue(profile.get("ftp_w", 200))
self._ftp.setStyleSheet(_field_ss())
self._max_hr_ov = QSpinBox(); self._max_hr_ov.setRange(0, 250)
self._max_hr_ov.setSuffix(" bpm (0=auto)")
self._max_hr_ov.setValue(profile.get("max_hr_override", 0))
self._max_hr_ov.setStyleSheet(_field_ss())
row("Weight", self._weight, 0)
row("Age", self._age, 1)
row("Resting HR", self._rest_hr, 2)
row("FTP", self._ftp, 3)
row("Max HR override", self._max_hr_ov, 4)
lay.addLayout(grid)
note = QLabel("FTP & zones power your training zone display and VO2max estimates.")
note.setStyleSheet(f"color:{COL_MUTED};font-size:10px;")
note.setWordWrap(True); lay.addWidget(note)
btns = QHBoxLayout()
cancel = QPushButton("Cancel"); cancel.setStyleSheet(_btn_style(COL_MUTED, 90))
cancel.clicked.connect(self.reject)
save = QPushButton("Save"); save.setStyleSheet(_btn_style(COL_SUCCESS, 90))
save.clicked.connect(self._save)
btns.addWidget(cancel); btns.addStretch(); btns.addWidget(save)
lay.addLayout(btns)
def _save(self):
self._result = {
"weight_kg": self._weight.value(),
"age": self._age.value(),
"resting_hr": self._rest_hr.value(),
"ftp_w": self._ftp.value(),
"max_hr_override": self._max_hr_ov.value(),
}
self.accept()
# ─── Post-workout summary dialog ──────────────────────────────────────────────
class PostWorkoutSummaryDialog(QDialog):
def __init__(self, summary: dict, new_pbs: dict, rider_totals: dict,
profile: dict, zone_p: list[int], zone_hr: list[int], parent=None):
super().__init__(parent)
self.setWindowTitle("Workout Summary")
self.setStyleSheet(f"background:{BG};color:{COL_WHITE};")
self.resize(700, 580)
main = QVBoxLayout(self)
main.setSpacing(10); main.setContentsMargins(20, 16, 20, 16)
# ── Header ────────────────────────────────────────────────────────────
rider = summary.get("rider", "") or "Guest"
dt = summary.get("date", "")[:16].replace("T", " ")
title = QLabel(f"🏁 {rider} · {dt}")
title.setStyleSheet(f"color:{COL_POWER};font-size:18px;font-weight:900;")
main.addWidget(title)
tabs = QTabWidget()
tabs.setStyleSheet(f"""
QTabWidget::pane {{border:1px solid {CARD_BORDER};border-radius:8px;background:{CARD_BG};}}
QTabBar::tab {{background:{BG};color:{COL_MUTED};padding:6px 18px;
border-radius:6px;font-size:12px;font-weight:700;}}
QTabBar::tab:selected {{background:{CARD_BG};color:{COL_WHITE};}}
""")
main.addWidget(tabs, stretch=1)
tabs.addTab(self._build_stats_tab(summary, new_pbs), "Stats")
tabs.addTab(self._build_zones_tab(zone_p, zone_hr, profile), "Zones")
tabs.addTab(self._build_totals_tab(rider_totals, profile, summary), "Totals & VO2")
close = QPushButton("Close")
close.setStyleSheet(_btn_style(COL_MUTED, 100))
close.clicked.connect(self.accept)
row = QHBoxLayout(); row.addStretch(); row.addWidget(close)
main.addLayout(row)
# ── Stats tab ─────────────────────────────────────────────────────────────
def _build_stats_tab(self, s: dict, new_pbs: dict) -> QWidget:
w = QWidget(); lay = QVBoxLayout(w); lay.setSpacing(8)
def dur_str(secs):
if not secs: return "--"
h, r = divmod(int(secs), 3600); m, s = divmod(r, 60)
return f"{h}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
rows = [
("Duration", dur_str(s.get("duration_seconds")), COL_TIME),
("Distance", f"{s['distance_m']/1000:.2f} km" if s.get("distance_m") else "--", COL_DIST),
("Calories", f"{s.get('total_calories', '--')} kcal", COL_CALS),
("Avg Power", f"{s.get('avg_power_w', '--')} W", COL_POWER),
("Max Power", f"{s.get('max_power_w', '--')} W", COL_POWER),
("Avg W/kg", f"{s.get('avg_wkg', '--')}", COL_WKG),
("Avg HR", f"{s.get('avg_hr', '--')} bpm", COL_HR),
("Max HR", f"{s.get('max_hr', '--')} bpm", COL_HR),
("Avg Cadence", f"{s.get('avg_cadence_rpm', '--')} rpm", COL_CADENCE),
("Max Cadence", f"{s.get('max_cadence_rpm', '--')} rpm", COL_CADENCE),
]
grid = QGridLayout(); grid.setSpacing(6)
for i, (label, val, color) in enumerate(rows):
is_pb = new_pbs.get(label.lower().replace(" ", "_"))
pb_tag = " 🏆 NEW PB!" if is_pb else ""
lbl = QLabel(label + ":"); lbl.setStyleSheet(f"color:{COL_MUTED};font-size:12px;")
v = QLabel(val + pb_tag)
v.setStyleSheet(f"color:{COL_GOLD if is_pb else color};font-size:13px;font-weight:700;")
grid.addWidget(lbl, i, 0)
grid.addWidget(v, i, 1)
grid.setColumnStretch(1, 1)
lay.addLayout(grid); lay.addStretch()
return w
# ── Zones tab ─────────────────────────────────────────────────────────────
def _build_zones_tab(self, zone_p: list[int], zone_hr: list[int], profile: dict) -> QWidget:
w = QWidget(); lay = QVBoxLayout(w); lay.setSpacing(12)
total_p = sum(zone_p) or 1
total_hr = sum(zone_hr) or 1
def zone_block(title, counts, zones, total):
frame = QFrame()
frame.setStyleSheet(
f"QFrame{{background:{BG};border:1px solid {CARD_BORDER};border-radius:8px;}}"
)
fl = QVBoxLayout(frame); fl.setContentsMargins(12, 8, 12, 8); fl.setSpacing(4)
hdr = QLabel(title)
hdr.setStyleSheet(f"color:{COL_MUTED};font-size:10px;font-weight:700;letter-spacing:1px;")
fl.addWidget(hdr)
for i, (lo, hi, name, color) in enumerate(zones):
secs = counts[i] if i < len(counts) else 0
pct = secs / total * 100
m, s = divmod(secs, 60)
row = QHBoxLayout(); row.setSpacing(8)
nl = QLabel(name); nl.setFixedWidth(130)
nl.setStyleSheet(f"color:{color};font-size:11px;font-weight:700;")
bar = QProgressBar(); bar.setRange(0, 100); bar.setValue(int(pct))
bar.setTextVisible(False); bar.setFixedHeight(12)
bar.setStyleSheet(f"""
QProgressBar {{background:{CARD_BORDER};border-radius:6px;border:none;}}
QProgressBar::chunk {{background:{color};border-radius:6px;}}
""")
tl = QLabel(f"{m:02d}:{s:02d} ({pct:.0f}%)")
tl.setFixedWidth(90)
tl.setStyleSheet(f"color:{COL_MUTED};font-size:10px;")
row.addWidget(nl); row.addWidget(bar, 1); row.addWidget(tl)
fl.addLayout(row)
return frame
lay.addWidget(zone_block("POWER ZONES (% FTP)", zone_p, POWER_ZONES, total_p))
lay.addWidget(zone_block("HR ZONES (HRR Karvonen)", zone_hr, HR_ZONES, total_hr))
ftp = profile.get("ftp_w", 0)
note = QLabel(f"FTP: {ftp} W Resting HR: {profile.get('resting_hr',0)} bpm "
f"Max HR: {_profile_max_hr(profile)} bpm")
note.setStyleSheet(f"color:{COL_MUTED};font-size:10px;")
lay.addWidget(note); lay.addStretch()
return w
# ── Totals & VO2 tab ──────────────────────────────────────────────────────
def _build_totals_tab(self, totals: dict, profile: dict, summary: dict) -> QWidget:
w = QWidget(); lay = QVBoxLayout(w); lay.setSpacing(10)
def fmt_time(secs):
h = int(secs) // 3600; m = (int(secs) % 3600) // 60
return f"{h}h {m:02d}m"
total_rows = [
("Workouts completed", str(totals.get("workout_count", 0)), COL_WHITE),
("Total time", fmt_time(totals.get("total_time_s", 0)), COL_TIME),
("Total distance", f"{totals.get('total_distance_km', 0):.1f} km", COL_DIST),
("Total calories", f"{totals.get('total_calories', 0):,} kcal", COL_CALS),
("Best avg power", f"{totals.get('best_avg_power', '--')} W", COL_POWER),
("All-time max power", f"{totals.get('max_power_w', '--')} W", COL_POWER),
("Best avg W/kg", f"{totals.get('best_avg_wkg', '--')}", COL_WKG),
]
hdr = QLabel("LIFETIME TOTALS")
hdr.setStyleSheet(f"color:{COL_MUTED};font-size:10px;font-weight:700;letter-spacing:1px;")
lay.addWidget(hdr)
grid = QGridLayout(); grid.setSpacing(6)
for i, (label, val, color) in enumerate(total_rows):
lbl = QLabel(label + ":"); lbl.setStyleSheet(f"color:{COL_MUTED};font-size:12px;")
v = QLabel(val); v.setStyleSheet(f"color:{color};font-size:13px;font-weight:700;")
grid.addWidget(lbl, i, 0); grid.addWidget(v, i, 1)
grid.setColumnStretch(1, 1)
lay.addLayout(grid)
# VO2max estimates
sep = QFrame(); sep.setFrameShape(QFrame.Shape.HLine)
sep.setStyleSheet(f"color:{CARD_BORDER};"); lay.addWidget(sep)
v2_hdr = QLabel("VO2 MAX ESTIMATES")
v2_hdr.setStyleSheet(f"color:{COL_MUTED};font-size:10px;font-weight:700;letter-spacing:1px;")
lay.addWidget(v2_hdr)
ftp = profile.get("ftp_w", 0)
wt = profile.get("weight_kg", 75)
rest = profile.get("resting_hr", 60)
prof_mhr = _profile_max_hr(profile)
# Use the higher of session-recorded max HR vs age-predicted — actual measurement wins
sess_mhr = summary.get("max_hr") or 0
best_mhr = max(sess_mhr, prof_mhr)
mhr_source = "recorded session max" if sess_mhr >= prof_mhr else f"estimated (220−age)"
shown_any = False
if ftp > 0:
v2p = vo2max_from_ftp(ftp, wt)
cls, cls_col = vo2max_classification(v2p)
ftp_wkg = round(ftp / wt, 2)
row = QHBoxLayout()
lbl = QLabel(f"Power {v2p} ml/kg/min")
lbl.setStyleSheet(f"color:{COL_POWER};font-size:14px;font-weight:800;")
cls_lbl = QLabel(f" {cls}")
cls_lbl.setStyleSheet(f"color:{cls_col};font-size:13px;font-weight:700;")
src_lbl = QLabel(f" via FTP {ftp} W ({ftp_wkg} W/kg)")
src_lbl.setStyleSheet(f"color:{COL_MUTED};font-size:11px;")
row.addWidget(lbl); row.addWidget(cls_lbl); row.addWidget(src_lbl); row.addStretch()
lay.addLayout(row)
shown_any = True
if rest > 0 and best_mhr > rest:
v2h = vo2max_from_hr(best_mhr, rest)
cls, cls_col = vo2max_classification(v2h)
row = QHBoxLayout()
lbl = QLabel(f"HR {v2h} ml/kg/min")
lbl.setStyleSheet(f"color:{COL_HR};font-size:14px;font-weight:800;")
cls_lbl = QLabel(f" {cls}")
cls_lbl.setStyleSheet(f"color:{cls_col};font-size:13px;font-weight:700;")
src_lbl = QLabel(f" max HR {best_mhr} bpm ({mhr_source}), rest {rest} bpm")
src_lbl.setStyleSheet(f"color:{COL_MUTED};font-size:11px;")
row.addWidget(lbl); row.addWidget(cls_lbl); row.addWidget(src_lbl); row.addStretch()
lay.addLayout(row)
shown_any = True
if not shown_any:
lay.addWidget(QLabel("Set your FTP and resting HR in the profile (⚙) to see estimates."))
note = QLabel(
"Power estimate: uses your FTP via Coggan / Hawley & Noakes (MAP = FTP ÷ 0.76).\n"
"HR estimate: Uth–Sørensen formula — uses the higher of session-recorded or age-predicted max HR.\n"
"Both are estimates. Lab VO2max testing gives the most accurate result."
)
note.setStyleSheet(f"color:{COL_MUTED};font-size:10px;"); note.setWordWrap(True)
lay.addWidget(note); lay.addStretch()
return w
# ─── Workout Builder dialog ───────────────────────────────────────────────────
class WorkoutBuilderDialog(QDialog):
def __init__(self, initial_plan: list[Segment] | None = None, parent=None):
super().__init__(parent)
self.setWindowTitle("Workout Builder")
self.setStyleSheet(f"background:{BG};color:{COL_WHITE};")
self.resize(860, 560)
self.result_plan: list[Segment] = []
self._segs: list[Segment] = copy.deepcopy(initial_plan or [])
lay = QVBoxLayout(self); lay.setSpacing(10); lay.setContentsMargins(16,14,16,14)
lay.addLayout(self._build_template_row())
lay.addWidget(self._build_table())
lay.addLayout(self._build_add_row())
lay.addLayout(self._build_bottom_row())
self._rebuild_table()
def _build_template_row(self) -> QHBoxLayout:
row = QHBoxLayout(); row.setSpacing(10)
lbl = QLabel("PRESET TEMPLATES")
lbl.setStyleSheet(f"color:{COL_MUTED};font-size:10px;font-weight:700;letter-spacing:1px;")
row.addWidget(lbl)
self._tmpl_combo = QComboBox()
self._tmpl_combo.addItem("— choose a template —")
self._tmpl_combo.addItems(list(WORKOUT_TEMPLATES.keys()))
self._tmpl_combo.setMinimumWidth(280); self._tmpl_combo.setStyleSheet(_field_ss())
row.addWidget(self._tmpl_combo)
load_btn = QPushButton("Load Template")
load_btn.setStyleSheet(_btn_style(COL_CADENCE, 130))
load_btn.clicked.connect(self._load_template); row.addWidget(load_btn)
row.addStretch()
self._total_lbl = QLabel("Total: 00:00")
self._total_lbl.setStyleSheet(f"color:{COL_MUTED};font-size:12px;font-weight:700;")
row.addWidget(self._total_lbl)
return row
def _build_table(self) -> QTableWidget:
self._tbl = QTableWidget(); self._tbl.setColumnCount(7)
self._tbl.setHorizontalHeaderLabels(["#","Segment","Duration","Target","Value","↑↓","✕"])
self._tbl.setStyleSheet(f"""
QTableWidget {{background:{CARD_BG};color:{COL_WHITE};
border:1px solid {CARD_BORDER};border-radius:8px;
gridline-color:{CARD_BORDER};font-size:12px;}}
QHeaderView::section {{background:#1a1a38;color:{COL_MUTED};
border:none;padding:5px 4px;font-size:10px;font-weight:700;letter-spacing:1px;}}
QTableWidget::item:selected {{background:#2a2a5a;}}
QComboBox,QSpinBox,QLineEdit {{background:#0d0d1a;color:{COL_WHITE};
border:1px solid {CARD_BORDER};border-radius:4px;padding:2px 4px;font-size:11px;}}
QComboBox::drop-down {{border:none;}}
""")
hdr = self._tbl.horizontalHeader()
for i, m in [(0, QHeaderView.ResizeMode.ResizeToContents),
(1, QHeaderView.ResizeMode.Stretch),
(2, QHeaderView.ResizeMode.ResizeToContents),
(3, QHeaderView.ResizeMode.ResizeToContents),
(4, QHeaderView.ResizeMode.ResizeToContents),
(5, QHeaderView.ResizeMode.ResizeToContents),
(6, QHeaderView.ResizeMode.ResizeToContents)]:
hdr.setSectionResizeMode(i, m)
self._tbl.verticalHeader().setVisible(False)
self._tbl.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self._tbl.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
return self._tbl
def _build_add_row(self) -> QHBoxLayout:
row = QHBoxLayout(); row.setSpacing(10)
add_lbl = QLabel("ADD"); add_lbl.setStyleSheet(f"color:{COL_MUTED};font-size:10px;font-weight:700;letter-spacing:1px;")
row.addWidget(add_lbl)
self._add_combo = QComboBox(); self._add_combo.addItems(SEGMENT_NAMES)
self._add_combo.setFixedWidth(120); self._add_combo.setStyleSheet(_field_ss())
row.addWidget(self._add_combo)
add_btn = QPushButton("+ Add Segment"); add_btn.setStyleSheet(_btn_style(COL_SPEED, 130))
add_btn.clicked.connect(self._add_segment); row.addWidget(add_btn)
row.addSpacing(20)
rep_lbl = QLabel("REPEAT selected rows"); rep_lbl.setStyleSheet(f"color:{COL_MUTED};font-size:10px;font-weight:700;letter-spacing:1px;")
row.addWidget(rep_lbl)
self._rep_spin = QSpinBox(); self._rep_spin.setRange(2,50); self._rep_spin.setValue(8)
self._rep_spin.setFixedWidth(60); self._rep_spin.setStyleSheet(_field_ss())
row.addWidget(self._rep_spin)
row.addWidget(QLabel("×"))
rep_btn = QPushButton("Repeat"); rep_btn.setStyleSheet(_btn_style(COL_CALS, 90))
rep_btn.clicked.connect(self._repeat_selected); row.addWidget(rep_btn)
row.addStretch()
clr_btn = QPushButton("Clear All"); clr_btn.setStyleSheet(_btn_style(COL_HR, 90))
clr_btn.clicked.connect(self._clear_all); row.addWidget(clr_btn)
return row
def _build_bottom_row(self) -> QHBoxLayout:
row = QHBoxLayout()
cancel = QPushButton("Cancel"); cancel.setStyleSheet(_btn_style(COL_MUTED, 100))
cancel.clicked.connect(self.reject); row.addWidget(cancel)
row.addStretch()
ok = QPushButton("✓ Load Workout"); ok.setStyleSheet(_btn_style(COL_POWER, 150))
ok.clicked.connect(self._accept); row.addWidget(ok)
return row
def _rebuild_table(self):
self._tbl.setRowCount(0)
for i, seg in enumerate(self._segs): self._insert_row(i, seg)
self._update_total()
def _insert_row(self, i: int, seg: Segment):
r = self._tbl.rowCount(); self._tbl.insertRow(r)
num = QTableWidgetItem(str(i+1)); num.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
num.setForeground(QColor(COL_MUTED)); self._tbl.setItem(r, 0, num)
name_cb = QComboBox(); name_cb.addItems(SEGMENT_NAMES)
name_cb.setCurrentText(seg.name if seg.name in SEGMENT_NAMES else "Custom")
name_cb.setStyleSheet(f"color:{seg.color};font-weight:700;"); self._tbl.setCellWidget(r, 1, name_cb)
dur_edit = QLineEdit(seg.duration_str); dur_edit.setAlignment(Qt.AlignmentFlag.AlignCenter)
dur_edit.setPlaceholderText("MM:SS"); self._tbl.setCellWidget(r, 2, dur_edit)
tgt_cb = QComboBox(); tgt_cb.addItems(["Open","Power","HR","Cadence"])
tgt_cb.setCurrentText(seg.target_type)
val_spin = QSpinBox(); val_spin.setRange(0, 5000); val_spin.setValue(seg.target_value)
val_spin.setEnabled(seg.target_type != "Open")
tgt_cb.currentTextChanged.connect(lambda t, s=val_spin: s.setEnabled(t != "Open"))
self._tbl.setCellWidget(r, 3, tgt_cb); self._tbl.setCellWidget(r, 4, val_spin)
ud = QWidget(); ul = QHBoxLayout(ud); ul.setContentsMargins(2,2,2,2); ul.setSpacing(2)
for sym, d in [("▲",-1),("▼",1)]:
b = QPushButton(sym); b.setFixedSize(24,24)
b.setStyleSheet(f"background:#1a1a38;color:{COL_MUTED};border:none;border-radius:4px;")
b.clicked.connect(lambda _, idx=i, dd=d: self._move_seg(idx, dd)); ul.addWidget(b)
self._tbl.setCellWidget(r, 5, ud)
del_btn = QPushButton("✕"); del_btn.setFixedSize(28, 24)
del_btn.setStyleSheet(f"background:{COL_HR}22;color:{COL_HR};border:1px solid {COL_HR}55;border-radius:4px;font-weight:700;")
del_btn.clicked.connect(lambda _, idx=i: self._remove_seg(idx)); self._tbl.setCellWidget(r, 6, del_btn)
self._tbl.setRowHeight(r, 36)
def _collect_segs(self) -> list[Segment]:
segs = []
for r in range(self._tbl.rowCount()):
name_w = self._tbl.cellWidget(r, 1); dur_w = self._tbl.cellWidget(r, 2)
tgt_w = self._tbl.cellWidget(r, 3); val_w = self._tbl.cellWidget(r, 4)
name = name_w.currentText() if name_w else "Custom"
ttype = tgt_w.currentText() if tgt_w else "Open"
tval = val_w.value() if val_w else 0
dur_s = 60
if dur_w:
txt = dur_w.text().strip()
try:
parts = txt.split(":")
dur_s = int(parts[0])*60+int(parts[1]) if len(parts)==2 else int(parts[0])
except (ValueError, IndexError): dur_s = 60
segs.append(Segment(name, max(1, dur_s), ttype, tval))
return segs
def _load_template(self):
key = self._tmpl_combo.currentText()
if key in WORKOUT_TEMPLATES:
self._segs = copy.deepcopy(WORKOUT_TEMPLATES[key]); self._rebuild_table()
def _add_segment(self):
self._segs = self._collect_segs()
pm = {"Warmup": Segment("Warmup",300,"Open"), "Work": Segment("Work",20,"Power",250),
"Sprint": Segment("Sprint",15,"Power",350), "Steady": Segment("Steady",600,"Power",160),
"Rest": Segment("Rest",10,"Power",80), "Recovery": Segment("Recovery",90,"Power",80),
"Cooldown": Segment("Cooldown",300,"Open"), "Custom": Segment("Custom",60,"Open")}
name = self._add_combo.currentText()
self._segs.append(copy.copy(pm.get(name, Segment(name,60,"Open")))); self._rebuild_table()
def _remove_seg(self, idx: int):
self._segs = self._collect_segs()