-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuploader_gui.py
More file actions
3316 lines (2807 loc) · 148 KB
/
Copy pathuploader_gui.py
File metadata and controls
3316 lines (2807 loc) · 148 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
# flake8: noqa: E501
# GUI application for Garmin Connect automatic uploader
# Line length limit relaxed for readability in GUI code
# Fix DPI scaling issues on Windows (must be before tkinter import)
import ctypes
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
ctypes.windll.user32.SetProcessDPIAware()
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, scrolledtext
import json
import os
import sys
import threading
import time
import datetime
import logging
import base64
import tempfile
import xml.etree.ElementTree as ET
import urllib.request
import urllib.error
from importlib.metadata import PackageNotFoundError, version as get_installed_package_version
try:
from garminconnect import Garmin
GARMINCONNECT_IMPORT_ERROR = None
except Exception as exc:
Garmin = None
GARMINCONNECT_IMPORT_ERROR = exc
try:
from fit_tool.base_type import BaseType as FitToolBaseType
from fit_tool.definition_message import DefinitionMessage as FitToolDefinitionMessage
from fit_tool.field import Field as FitToolField
from fit_tool.fit_file import FitFile as FitToolFitFile
from fit_tool.fit_file_builder import FitFileBuilder as FitToolFitFileBuilder
from fit_tool.profile.messages.activity_message import ActivityMessage as FitToolActivityMessage
from fit_tool.profile.messages.device_info_message import DeviceInfoMessage as FitToolDeviceInfoMessage
from fit_tool.profile.messages.file_creator_message import FileCreatorMessage as FitToolFileCreatorMessage
from fit_tool.profile.messages.file_id_message import FileIdMessage as FitToolFileIdMessage
from fit_tool.profile.profile_type import Manufacturer as FitToolManufacturer
FIT_TOOL_IMPORT_ERROR = None
except Exception as exc:
FitToolBaseType = None
FitToolDefinitionMessage = None
FitToolField = None
FitToolFitFile = None
FitToolFitFileBuilder = None
FitToolActivityMessage = None
FitToolDeviceInfoMessage = None
FitToolFileCreatorMessage = None
FitToolFileIdMessage = None
FitToolManufacturer = None
FIT_TOOL_IMPORT_ERROR = exc
from PIL import Image, ImageTk
from pystray import Icon, Menu, MenuItem
import webbrowser
import shutil
try:
import fitdecode
except ImportError:
fitdecode = None
try:
import keyring
except ImportError:
keyring = None # Falls back to config file storage if not available
# Configuration file (resolved to absolute path after _get_base_and_log_dirs)
_CONFIG_FILENAME = "uploader_config.json"
# Compute stable base/log directories so compiled builds reuse the same log in the exe folder
def _get_base_and_log_dirs():
# Prefer the real executable/launcher location (handles Nuitka/PyInstaller onefile)
if getattr(sys, "frozen", False) or "__compiled__" in globals():
exe_path = os.path.abspath(sys.argv[0]) if sys.argv else os.path.abspath(sys.executable)
exe_dir = os.path.dirname(exe_path)
# BASE_DIR remains the embedded resource dir when available; fall back to exe dir
base_dir = getattr(sys, "_MEIPASS", exe_dir)
return base_dir, exe_dir
# Script mode
script_dir = os.path.dirname(os.path.abspath(__file__))
return script_dir, script_dir
def _should_prefer_parent_files(default_dir):
if not (getattr(sys, "frozen", False) or "__compiled__" in globals()):
return True
bundle_markers = (
os.path.join(default_dir, "python311.dll"),
os.path.join(default_dir, "assets"),
os.path.join(default_dir, "tcl"),
)
return any(os.path.exists(marker) for marker in bundle_markers)
def _resolve_existing_or_default(filename, default_dir):
"""Return a path for config/log files, preferring existing files.
Priority:
- Existing file in the parent of default_dir (shared across versioned folders)
- Existing file in default_dir (legacy behavior)
- Otherwise, create in the parent of default_dir when safe, else in default_dir
"""
parent_dir = os.path.dirname(default_dir) if default_dir else ""
parent_path = os.path.join(parent_dir, filename) if parent_dir else ""
prefer_parent = _should_prefer_parent_files(default_dir)
# Prefer an existing file in the parent directory so multiple versioned
# folders (or different builds) automatically share the same files.
if prefer_parent and parent_path and os.path.isfile(parent_path):
return parent_path
# Fall back to any existing file in the current (exe) directory to remain
# compatible with older versions that wrote files there.
current_path = os.path.join(default_dir, filename) if default_dir else filename
if os.path.isfile(current_path):
return current_path
# No existing file anywhere: decide where to create a new one.
# Prefer the parent directory when it is a normal folder (not a drive root),
# so future versioned folders will automatically reuse it.
def _is_drive_root(path: str) -> bool:
if not path:
return False
drive, tail = os.path.splitdrive(path)
tail = tail.replace("/", "\\").rstrip("\\")
# e.g. "C:\\" -> tail == ""
return bool(drive) and tail == ""
if prefer_parent and parent_dir and not _is_drive_root(parent_dir):
return parent_path
# As a last resort (e.g. onefile exe placed directly in an app folder
# whose parent is the drive root), create the file next to the exe.
return current_path
BASE_DIR, LOG_DIR = _get_base_and_log_dirs()
CONFIG_FILE = _resolve_existing_or_default(_CONFIG_FILENAME, LOG_DIR)
def find_resource(filename):
"""Return first existing path for bundled/static assets."""
candidates = [
os.path.join(BASE_DIR, filename),
os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])) if sys.argv else "", filename),
os.path.join(os.path.dirname(os.path.abspath(sys.executable)) if hasattr(sys, "executable") else "", filename),
]
for path in candidates:
if path and os.path.exists(path):
return path
return os.path.join(BASE_DIR, filename)
LOGO_PATH = find_resource(os.path.join("assets", "garmin-uploader-logo.PNG"))
DEV_LOGO_PATH = find_resource(os.path.join("assets", "inc21.webp"))
GITHUB_LOGO_PATH = find_resource(os.path.join("assets", "github_logo.png"))
WAHOO_LOGO_PATH = find_resource(os.path.join("assets", "wahoo.png"))
MYWHOOSH_LOGO_PATH = find_resource(os.path.join("assets", "mywhoosh.png"))
TRAINERDAY_LOGO_PATH = find_resource(os.path.join("assets", "trainerday.png"))
VERSION = "1.1.2"
GITHUB_REPO_URL = "https://github.com/Inc21/Garmin-Connect-Auto-Uploader"
VERSION_JSON_URL = "https://raw.githubusercontent.com/Inc21/Garmin-Connect-Auto-Uploader/main/version.json"
LEGACY_VERSION_JSON_URL = "https://raw.githubusercontent.com/Inc21/Wahoo-and-MyWhoos-to-Garmin-Conect-Auto-Uploader/main/version.json"
GARMIN_SPOOF_DEVICE_NAME = "Garmin Edge 530"
GARMIN_SPOOF_UNIT_ID = 1234567890
GARMIN_SPOOF_PRODUCT_ID = 3121
GARMIN_SPOOF_SOFTWARE_VERSION = 17.0
GARMIN_SPOOF_VERSION_MAJOR = 17
GARMIN_SPOOF_VERSION_MINOR = 0
MIN_GARMINCONNECT_VERSION = "0.3.2"
RECOMMENDED_GARMINCONNECT_VERSION = "0.3.2"
LOG_FILE = _resolve_existing_or_default("garmin_uploader.log", LOG_DIR)
# Upload log (single file; month separators written when month changes)
UPLOAD_LOG_FILE = _resolve_existing_or_default("garmin_uploads.log", LOG_DIR)
MAX_LOG_SIZE_MB = 10 # Rotate log after 10MB
# Setup logging with rotation (standard format without icons by default)
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler(
LOG_FILE,
maxBytes=MAX_LOG_SIZE_MB * 1024 * 1024, # 10MB
backupCount=3, # Keep 3 backup files (~ 3 months of logs)
encoding='utf-8'
)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logging.basicConfig(
level=logging.INFO,
handlers=[file_handler, console_handler],
force=True
)
logger = logging.getLogger(__name__)
def _version_key(version_text):
parts = []
for raw_part in str(version_text).split("."):
digits = "".join(ch for ch in raw_part if ch.isdigit())
parts.append(int(digits) if digits else 0)
while len(parts) < 3:
parts.append(0)
return tuple(parts[:3])
def _get_installed_garminconnect_version():
try:
return get_installed_package_version("garminconnect")
except PackageNotFoundError:
return None
except Exception as exc:
logger.warning(f"Could not read installed garminconnect version: {exc}")
return None
def ensure_supported_garminconnect():
installed_version = _get_installed_garminconnect_version()
if GARMINCONNECT_IMPORT_ERROR is not None:
logger.error(f"garminconnect import failed: {GARMINCONNECT_IMPORT_ERROR}")
messagebox.showerror(
"Unsupported Garmin Login Library",
"Garmin Connect support could not be loaded.\n\n"
f"Installed garminconnect version: {installed_version or 'not installed'}\n"
f"Import error: {GARMINCONNECT_IMPORT_ERROR}\n\n"
f"This app requires garminconnect {MIN_GARMINCONNECT_VERSION} or newer.\n"
f"The recommended version is {RECOMMENDED_GARMINCONNECT_VERSION}.\n\n"
"Please reinstall dependencies from requirements.txt and rebuild the app."
)
return False
if not installed_version:
logger.error("garminconnect is not installed")
messagebox.showerror(
"Unsupported Garmin Login Library",
"garminconnect is not installed.\n\n"
f"This app requires garminconnect {MIN_GARMINCONNECT_VERSION} or newer.\n"
f"The recommended version is {RECOMMENDED_GARMINCONNECT_VERSION}.\n\n"
"Please reinstall dependencies from requirements.txt and rebuild the app."
)
return False
logger.info(f"Detected garminconnect {installed_version}")
if _version_key(installed_version) < _version_key(MIN_GARMINCONNECT_VERSION):
logger.error(
f"Unsupported garminconnect version detected: {installed_version}. "
f"Minimum supported version is {MIN_GARMINCONNECT_VERSION}."
)
messagebox.showerror(
"Unsupported Garmin Login Library",
f"This build is using garminconnect {installed_version}.\n\n"
f"Garmin Connect Uploader v{VERSION} requires garminconnect "
f"{MIN_GARMINCONNECT_VERSION} or newer.\n"
f"The recommended version is {RECOMMENDED_GARMINCONNECT_VERSION}.\n\n"
"Please reinstall dependencies from requirements.txt and rebuild the app."
)
return False
if _version_key(installed_version) < _version_key(RECOMMENDED_GARMINCONNECT_VERSION):
logger.warning(
f"garminconnect {installed_version} is supported but older than the recommended "
f"version {RECOMMENDED_GARMINCONNECT_VERSION}."
)
return True
# Dedicated upload-only logger (separate file, no rotation; date markers in file)
upload_logger = logging.getLogger("upload_log")
upload_handler = logging.FileHandler(UPLOAD_LOG_FILE, encoding='utf-8')
upload_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
upload_logger.setLevel(logging.INFO)
# Avoid duplicate propagation to root; we want a clean uploads-only file
upload_logger.propagate = False
upload_logger.handlers = [upload_handler]
# Custom log functions with icons for specific events
def log_success(message):
"""Log a success message with green checkmark"""
logger.info(f"✅ {message}")
def log_error(message):
"""Log an error message with red X"""
logger.error(f"❌ {message}")
def log_warning(message):
"""Log a warning message with warning sign"""
logger.warning(f"⚠️ {message}")
def log_info(message):
"""Log an info message (no icon)"""
logger.info(message)
def log_separator():
"""Add a blank line separator in logs for better grouping"""
# Write directly to handlers to create a true blank line
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
handler.stream.write("\n")
handler.flush()
KEYRING_SERVICE = "GarminConnectUploader"
def store_password(email, password):
"""Store password securely using Windows Credential Manager via keyring"""
if not password or not email:
return
if keyring:
try:
keyring.set_password(KEYRING_SERVICE, email, password)
return
except Exception:
pass
logger.warning("keyring not available; password only in config file fallback")
def _encode_fallback(password):
"""Simple base64 encoding for config-file fallback (not a security measure)"""
if not password:
return ""
return "b64:" + base64.b64encode(password.encode('utf-8')).decode('utf-8')
def _decode_fallback(encoded):
"""Decode base64 config-file fallback password"""
if not encoded:
return ""
if encoded.startswith("b64:"):
try:
return base64.b64decode(encoded[4:].encode('utf-8')).decode('utf-8')
except Exception:
return ""
# Try legacy XOR+Base64 format
return _legacy_decrypt_password(encoded)
def retrieve_password(email):
"""Retrieve password from Windows Credential Manager via keyring"""
if not email:
return ""
if keyring:
try:
pw = keyring.get_password(KEYRING_SERVICE, email)
if pw:
return pw
except Exception:
pass
return ""
def delete_password(email):
"""Remove stored password from keyring"""
if not email:
return
if keyring:
try:
keyring.delete_password(KEYRING_SERVICE, email)
except Exception:
pass
def _legacy_decrypt_password(encrypted_password):
"""Decrypt password from old XOR+Base64 format for migration only"""
if not encrypted_password:
return ""
try:
key = "GarminUploaderV1SecretKey2024"
decoded = base64.b64decode(
encrypted_password.encode('utf-8')
).decode('latin-1')
decrypted = ''.join(
chr(ord(c) ^ ord(key[i % len(key)]))
for i, c in enumerate(decoded)
)
return decrypted
except Exception: # noqa: E722
return ""
class ConnectUploaderGUI:
def __init__(self, root):
self.root = root
self.root.title(f"Garmin Connect Uploader v{VERSION}")
# Get DPI scaling factor
scaling = self.root.tk.call('tk', 'scaling')
self.scaling = scaling # Store for use in dialog windows
# Base dimensions at 96 DPI (1.0 scaling)
base_width = 600
base_min_height = 650 # Minimum for small screens
base_max_height = 900 # Maximum initial height
# Adjust for actual DPI scaling
width = int(base_width * (scaling / 1.33))
min_height = int(base_min_height * (scaling / 1.33))
max_height = int(base_max_height * (scaling / 1.33))
# Start with minimum height, will auto-size after UI is built
self.root.geometry(f"{width}x{min_height}")
self.root.minsize(width, min_height)
self.root.resizable(True, True)
# Store base and max dimensions for later use
self._base_width = width
self._min_height = min_height
self._max_height = max_height
# Set modern styling
style = ttk.Style()
style.theme_use('clam') # More modern theme
# Configure colors
style.configure('TLabel', background='#f0f0f0')
style.configure('TFrame', background='#f0f0f0')
style.configure('TButton', padding=6)
style.configure('Header.TLabel', font=('Arial', 11, 'bold'), background='#f0f0f0')
style.configure('Title.TLabel', font=('Arial', 16, 'bold'), background='#f0f0f0', foreground='#2c3e50')
# Set window background
self.root.configure(bg='#f0f0f0')
# Set window icon
try:
if os.path.exists(LOGO_PATH):
logo_img = Image.open(LOGO_PATH)
logo_photo = ImageTk.PhotoImage(logo_img)
self.root.iconphoto(True, logo_photo)
self.logo_image = logo_photo # Keep reference
except Exception as e:
print(f"Could not load logo: {e}")
# Load saved configuration
self.config = self.load_config()
# Monitoring state
self.is_monitoring = False
self.monitor_thread = None
self.garmin_client = None
self.tray_icon = None
self.check_interval = 300 # Default 5 minutes
self.settings_changed = False # Track if settings have been modified
self._upload_log_day = None # Track day marker for uploads log
self.create_widgets()
self.load_settings()
self.load_last_sync_from_log() # Restore last sync/upload info
self.check_old_version_shortcut() # Check and update old version shortcuts
# Handle window close (minimize to tray if monitoring)
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Initialize garmin session directory
self.session_dir = os.path.join(os.path.expanduser("~"), "AppData", "Local", "GarminUploader", "session")
os.makedirs(self.session_dir, exist_ok=True)
# Initialize login state (will be set by try_session_login if successful)
self.garmin_client = None
self.is_logged_in = False
# Try to login quietly with saved session on startup
self.try_session_login()
def prompt_mfa_code(self):
"""Prompt user for MFA code using a tkinter dialog"""
mfa_code = tk.StringVar()
dialog = tk.Toplevel(self.root)
dialog.title("Two-Factor Authentication")
dialog.geometry("400x180")
dialog.transient(self.root)
dialog.grab_set()
# Center the dialog
dialog.update_idletasks()
x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
dialog.geometry(f"+{x}+{y}")
frame = ttk.Frame(dialog, padding="20")
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="🔐 Two-Factor Authentication Required", font=('Segoe UI', 11, 'bold')).pack(pady=(0, 10))
ttk.Label(frame, text="Enter the verification code from your authenticator app:", wraplength=350).pack(pady=(0, 10))
entry = ttk.Entry(frame, textvariable=mfa_code, font=('Segoe UI', 11), width=20, justify='center')
entry.pack(pady=(0, 15))
entry.focus_set()
def on_submit():
dialog.destroy()
entry.bind('<Return>', lambda e: on_submit())
btn_frame = ttk.Frame(frame)
btn_frame.pack()
ttk.Button(btn_frame, text="Submit", command=on_submit).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="Cancel", command=lambda: [mfa_code.set(''), dialog.destroy()]).pack(side=tk.LEFT, padx=5)
dialog.wait_window()
return mfa_code.get().strip()
def try_session_login(self):
"""Try to login using saved session tokens (garminconnect 0.3.1 API)"""
try:
email = self.garmin_email.get() if self.garmin_email else self.config.get('garmin_email', '')
password = self.garmin_password.get() if self.garmin_password else self.config.get('garmin_password', '')
if not email or not password:
return False
# Create session directory specific to this user
user_session_dir = os.path.join(self.session_dir, email.replace('@', '_').replace('.', '_'))
# Try to resume session using saved tokens
if os.path.exists(user_session_dir):
try:
# Create Garmin client and try to login with saved tokens
self.garmin_client = Garmin()
self.garmin_client.login(user_session_dir)
logger.info("Successfully resumed session using saved tokens (no login required)")
self.update_status("Logged in using saved session", "green")
self.update_login_status(True)
return True
except Exception as e:
# Session failed, fall back to credentials
self.garmin_client = None
logger.warning(f"Session login failed, will use credentials: {str(e)}")
pass
except Exception as e:
self.garmin_client = None
logger.warning(f"Session login failed: {str(e)}")
pass
return False
def create_widgets(self):
# Create canvas with scrollbar for content
canvas = tk.Canvas(self.root, bg='#f0f0f0', highlightthickness=0)
scrollbar = ttk.Scrollbar(self.root, orient="vertical", command=canvas.yview)
# Main container inside canvas
main_frame = ttk.Frame(canvas, padding="20")
self._canvas = canvas
self._main_frame = main_frame
# Configure grid weights for responsive layout
main_frame.columnconfigure(1, weight=1) # Column 1 (entry fields) expands
main_frame.columnconfigure(2, weight=1) # Column 2 also expands
# Configure canvas
canvas.configure(yscrollcommand=scrollbar.set)
# Pack scrollbar and canvas
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Create window in canvas
canvas_frame = canvas.create_window((0, 0), window=main_frame, anchor="nw")
# Create a single global scroll handler
def on_mousewheel(event):
# event.delta works for Windows; use factor of 120 for smooth scrolling
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
return "break"
# Bind the wheel only when the mouse enters the canvas area
canvas.bind("<Enter>", lambda _: canvas.bind_all("<MouseWheel>", on_mousewheel))
canvas.bind("<Leave>", lambda _: canvas.unbind_all("<MouseWheel>"))
# Add Linux support (optional but good practice)
canvas.bind("<Enter>", lambda _: canvas.bind_all("<Button-4>", lambda e: canvas.yview_scroll(-1, "units")), add="+")
canvas.bind("<Enter>", lambda _: canvas.bind_all("<Button-5>", lambda e: canvas.yview_scroll(1, "units")), add="+")
canvas.bind("<Leave>", lambda _: canvas.unbind_all("<Button-4>"), add="+")
canvas.bind("<Leave>", lambda _: canvas.unbind_all("<Button-5>"), add="+")
# Update scroll region and make frame fill canvas width
def on_frame_configure(event):
# Only enable scrolling when content exceeds canvas size
canvas.update_idletasks() # Ensure sizes are calculated
frame_height = main_frame.winfo_reqheight()
canvas_height = canvas.winfo_height()
if frame_height > canvas_height:
# Content exceeds canvas, enable scrolling
canvas.configure(scrollregion=canvas.bbox("all"))
else:
# Content fits, disable scrolling
canvas.configure(scrollregion=(0, 0, canvas.winfo_width(), canvas_height))
# Bind mousewheel to canvas
def on_mousewheel(event):
# Scroll the canvas regardless of content size
# Use the event.delta to determine scroll direction
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
return "break" # Prevent propagation
def on_canvas_configure(event):
# Make the frame fill the canvas width
canvas.itemconfig(canvas_frame, width=event.width)
# Update scroll region when canvas is resized
canvas.update_idletasks() # Ensure sizes are calculated
frame_height = main_frame.winfo_reqheight()
canvas_height = canvas.winfo_height()
if frame_height > canvas_height:
# Content exceeds canvas, enable scrolling
canvas.configure(scrollregion=canvas.bbox("all"))
else:
# Content fits, disable scrolling
canvas.configure(scrollregion=(0, 0, event.width, canvas_height))
main_frame.bind("<Configure>", on_frame_configure)
canvas.bind("<Configure>", on_canvas_configure)
# Title with logo
title_frame = ttk.Frame(main_frame)
title_frame.grid(row=0, column=0, columnspan=3, pady=(0, 25))
# Load and display logo
try:
logo_img = Image.open(LOGO_PATH)
logo_img.thumbnail((45, 45)) # Resize to 45x45
self.title_logo = ImageTk.PhotoImage(logo_img)
logo_label = ttk.Label(title_frame, image=self.title_logo)
logo_label.pack(side=tk.LEFT, padx=(0, 10))
except Exception:
pass # If logo fails to load, just skip it
# Title text
ttk.Label(title_frame, text="Garmin Connect Uploader", style='Title.TLabel').pack(side=tk.LEFT)
# Garmin Settings
ttk.Label(main_frame, text="🔑 Garmin Connect Settings", style='Header.TLabel').grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=(10, 5))
# Quick link to Garmin Connect
garmin_link = ttk.Label(
main_frame,
text="Open Garmin Connect in Browser",
foreground='blue',
cursor='hand2',
font=('Arial', 9, 'underline')
)
garmin_link.grid(row=1, column=2, sticky=tk.E, pady=(10, 5))
garmin_link.bind(
"<Button-1>",
lambda e: webbrowser.open("https://connect.garmin.com")
)
ttk.Label(main_frame, text="Email:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.garmin_email = ttk.Entry(main_frame, width=35)
self.garmin_email.grid(row=2, column=1, sticky=tk.W, pady=5, padx=5)
self.garmin_email.bind('<KeyRelease>', lambda e: self.on_credentials_changed())
ttk.Label(main_frame, text="Password:").grid(row=3, column=0, sticky=tk.W, pady=5)
self.garmin_password = ttk.Entry(main_frame, show="*", width=35)
self.garmin_password.grid(row=3, column=1, sticky=tk.W, pady=5, padx=5)
self.garmin_password.bind('<KeyRelease>', lambda e: self.on_credentials_changed())
# Test Connection button and login status indicator
test_btn = ttk.Button(main_frame, text="Test & Login", command=self.test_garmin_connection)
test_btn.grid(row=3, column=2, sticky=tk.W, pady=5, padx=5)
# Login status indicator (initially hidden)
self.login_status_label = ttk.Label(main_frame, text="", foreground="green", font=('Segoe UI', 9))
self.login_status_label.grid(row=2, column=2, sticky=tk.W, pady=5, padx=5)
# Folder Settings
ttk.Label(main_frame, text="📁 Folder Settings", style='Header.TLabel').grid(row=4, column=0, columnspan=3, sticky=tk.W, pady=(20, 5))
# Per-app expanded state for collapsible sections (default collapsed)
self.wahoo_expanded = tk.BooleanVar(value=False)
self.mywhoosh_expanded = tk.BooleanVar(value=False)
self.trainerday_expanded = tk.BooleanVar(value=False)
# Wahoo section (checkbox header + collapsible body)
self.wahoo_section = ttk.Frame(main_frame)
self.wahoo_section.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E))
wahoo_header = ttk.Frame(self.wahoo_section)
wahoo_header.pack(fill='x', pady=(2, 0))
wahoo_header.bind("<Button-1>", lambda e: self._on_header_click("wahoo", e))
self.wahoo_toggle = ttk.Label(wahoo_header, text="▶", width=2)
self.wahoo_toggle.pack(side='left')
self.wahoo_toggle.bind("<Button-1>", lambda e: self._on_header_click("wahoo", e))
try:
wahoo_img = Image.open(WAHOO_LOGO_PATH)
wahoo_img.thumbnail((28, 28))
self.wahoo_logo_image = ImageTk.PhotoImage(wahoo_img)
wahoo_logo_label = ttk.Label(wahoo_header, image=self.wahoo_logo_image)
wahoo_logo_label.pack(side='left', padx=(2, 4))
wahoo_logo_label.bind("<Button-1>", lambda e: self._on_header_click("wahoo", e))
except Exception:
self.wahoo_logo_image = None
# App name label (no checkbox; status-only header)
wahoo_name_label = ttk.Label(wahoo_header, text="Wahoo (Dropbox)")
wahoo_name_label.pack(side='left')
wahoo_name_label.bind("<Button-1>", lambda e: self._on_header_click("wahoo", e))
# Status label on the right (e.g. Not configured / Folder missing / ✅ Ready)
self.wahoo_status_label = ttk.Label(wahoo_header, text="", foreground='gray')
self.wahoo_status_label.pack(side='right')
self.wahoo_status_label.bind("<Button-1>", lambda e: self._on_header_click("wahoo", e))
self.wahoo_body = ttk.Frame(self.wahoo_section)
self.wahoo_body.pack(fill='x', padx=(24, 0), pady=(0, 4))
self.wahoo_body.columnconfigure(0, weight=1)
self.wahoo_folder = ttk.Entry(self.wahoo_body)
self.wahoo_folder.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 5), pady=(0, 2))
self.wahoo_folder.bind('<KeyRelease>', lambda e: (self.mark_settings_changed(), self._update_app_status_icons()))
ttk.Button(self.wahoo_body, text="Browse", command=lambda: self.browse_folder(self.wahoo_folder)).grid(row=0, column=1, padx=(0, 3), pady=(0, 2))
help_btn = ttk.Button(self.wahoo_body, text="?", command=self.show_wahoo_help, width=2)
help_btn.grid(row=0, column=2, pady=(0, 2))
ttk.Label(
self.wahoo_body,
text="Example: C\\Users\\YourName\\Dropbox\\Apps\\WahooFitness",
font=('Arial', 8),
foreground='gray',
).grid(row=1, column=0, columnspan=3, sticky=tk.W)
# MyWhoosh section
self.mywhoosh_section = ttk.Frame(main_frame)
self.mywhoosh_section.grid(row=6, column=0, columnspan=3, sticky=(tk.W, tk.E))
mywhoosh_header = ttk.Frame(self.mywhoosh_section)
mywhoosh_header.pack(fill='x', pady=(8, 0))
mywhoosh_header.bind("<Button-1>", lambda e: self._on_header_click("mywhoosh", e))
self.mywhoosh_toggle = ttk.Label(mywhoosh_header, text="▶", width=2)
self.mywhoosh_toggle.pack(side='left')
self.mywhoosh_toggle.bind("<Button-1>", lambda e: self._on_header_click("mywhoosh", e))
try:
mywhoosh_img = Image.open(MYWHOOSH_LOGO_PATH)
mywhoosh_img.thumbnail((28, 28))
self.mywhoosh_logo_image = ImageTk.PhotoImage(mywhoosh_img)
mywhoosh_logo_label = ttk.Label(mywhoosh_header, image=self.mywhoosh_logo_image)
mywhoosh_logo_label.pack(side='left', padx=(2, 4))
mywhoosh_logo_label.bind("<Button-1>", lambda e: self._on_header_click("mywhoosh", e))
except Exception:
self.mywhoosh_logo_image = None
mywhoosh_name_label = ttk.Label(mywhoosh_header, text="MyWhoosh")
mywhoosh_name_label.pack(side='left')
mywhoosh_name_label.bind("<Button-1>", lambda e: self._on_header_click("mywhoosh", e))
self.mywhoosh_status_label = ttk.Label(mywhoosh_header, text="", foreground='gray')
self.mywhoosh_status_label.pack(side='right')
self.mywhoosh_status_label.bind("<Button-1>", lambda e: self._on_header_click("mywhoosh", e))
self.mywhoosh_body = ttk.Frame(self.mywhoosh_section)
self.mywhoosh_body.pack(fill='x', padx=(24, 0), pady=(0, 4))
self.mywhoosh_body.columnconfigure(0, weight=1)
self.mywhoosh_folder = ttk.Entry(self.mywhoosh_body)
self.mywhoosh_folder.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 5), pady=(0, 2))
self.mywhoosh_folder.bind('<KeyRelease>', lambda e: (self.mark_settings_changed(), self._update_app_status_icons()))
ttk.Button(self.mywhoosh_body, text="Browse", command=lambda: self.browse_folder(self.mywhoosh_folder)).grid(row=0, column=1, padx=(0, 3), pady=(0, 2))
help_btn2 = ttk.Button(self.mywhoosh_body, text="?", command=self.show_mywhoosh_help, width=2)
help_btn2.grid(row=0, column=2, pady=(0, 2))
ttk.Label(
self.mywhoosh_body,
text="Example: C\\Users\\YourName\\AppData\\Local\\...\\MyWhoosh\\Content\\Data",
font=('Arial', 8),
foreground='gray',
).grid(row=1, column=0, columnspan=3, sticky=tk.W)
# MyWhoosh warning and link inside the body
warning_frame = ttk.Frame(self.mywhoosh_body)
warning_frame.grid(row=2, column=0, columnspan=3, sticky=tk.W, pady=(8, 0))
icon_label = ttk.Label(warning_frame, text="⚠️", font=('Arial', 20), foreground='#ff6600')
icon_label.grid(row=0, column=0, rowspan=2, sticky='n', padx=(0, 10))
ttk.Label(
warning_frame,
text="MyWhoosh only keeps the latest activity in the cache folder.",
font=('Arial', 9),
foreground='#ff6600',
).grid(row=0, column=1, sticky='w')
ttk.Label(
warning_frame,
text="Multiple rides while app is closed = only the last one syncs!",
font=('Arial', 9),
foreground='#ff6600',
).grid(row=1, column=1, sticky='w')
link_frame = ttk.Frame(self.mywhoosh_body)
link_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(5, 0))
readme_link = ttk.Label(
link_frame,
text="Read more on GitHub",
foreground='blue',
cursor='hand2',
font=('Arial', 9, 'underline'),
)
readme_link.pack(anchor='center')
readme_link.bind(
"<Button-1>",
lambda e: webbrowser.open(
"https://github.com/Inc21/Wahoo-and-MyWhoosh-to-Garmin-Conect-Auto-Uploader#%EF%B8%8F-important-sync-behavior"
),
)
# TrainerDay section (similar structure to Wahoo)
self.trainerday_section = ttk.Frame(main_frame)
self.trainerday_section.grid(row=7, column=0, columnspan=3, sticky=(tk.W, tk.E))
trainerday_header = ttk.Frame(self.trainerday_section)
trainerday_header.pack(fill='x', pady=(8, 0))
trainerday_header.bind("<Button-1>", lambda e: self._on_header_click("trainerday", e))
self.trainerday_toggle = ttk.Label(trainerday_header, text="▶", width=2)
self.trainerday_toggle.pack(side='left')
self.trainerday_toggle.bind("<Button-1>", lambda e: self._on_header_click("trainerday", e))
try:
trainerday_img = Image.open(TRAINERDAY_LOGO_PATH)
trainerday_img.thumbnail((28, 28))
self.trainerday_logo_image = ImageTk.PhotoImage(trainerday_img)
trainerday_logo_label = ttk.Label(trainerday_header, image=self.trainerday_logo_image)
trainerday_logo_label.pack(side='left', padx=(2, 4))
trainerday_logo_label.bind("<Button-1>", lambda e: self._on_header_click("trainerday", e))
except Exception:
self.trainerday_logo_image = None
trainerday_name_label = ttk.Label(trainerday_header, text="TrainerDay (Dropbox)")
trainerday_name_label.pack(side='left')
trainerday_name_label.bind("<Button-1>", lambda e: self._on_header_click("trainerday", e))
self.trainerday_status_label = ttk.Label(trainerday_header, text="", foreground='gray')
self.trainerday_status_label.pack(side='right')
self.trainerday_status_label.bind("<Button-1>", lambda e: self._on_header_click("trainerday", e))
self.trainerday_body = ttk.Frame(self.trainerday_section)
self.trainerday_body.pack(fill='x', padx=(24, 0), pady=(0, 4))
self.trainerday_body.columnconfigure(0, weight=1)
self.trainerday_folder = ttk.Entry(self.trainerday_body)
self.trainerday_folder.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 5), pady=(0, 2))
self.trainerday_folder.bind('<KeyRelease>', lambda e: (self.mark_settings_changed(), self._update_app_status_icons()))
ttk.Button(self.trainerday_body, text="Browse", command=lambda: self.browse_folder(self.trainerday_folder)).grid(row=0, column=1, padx=(0, 3), pady=(0, 2))
help_btn3 = ttk.Button(self.trainerday_body, text="?", command=self.show_trainerday_help, width=2)
help_btn3.grid(row=0, column=2, pady=(0, 2))
ttk.Label(
self.trainerday_body,
text="Example: C\\Users\\YourName\\Dropbox\\Apps\\TrainerDay",
font=('Arial', 8),
foreground='gray',
).grid(row=1, column=0, columnspan=3, sticky=tk.W)
# Experimental spoof setting
self.experimental_edge_spoof = tk.BooleanVar(value=False)
experimental_frame = ttk.Frame(main_frame)
experimental_frame.grid(row=12, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(8, 2))
ttk.Checkbutton(
experimental_frame,
text="Experimental Garmin mode",
variable=self.experimental_edge_spoof,
command=self.mark_settings_changed,
).pack(side='left', anchor='w')
ttk.Button(
experimental_frame,
text="i",
width=2,
command=self.show_experimental_spoof_info,
).pack(side='left', padx=(6, 0))
# Separator
ttk.Separator(main_frame, orient='horizontal').grid(row=13, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=15)
# Auto-Start Settings
ttk.Label(main_frame, text="⏰ Auto-Start Settings", style='Header.TLabel').grid(row=14, column=0, columnspan=3, sticky=tk.W, pady=(5, 5))
# Helpful note
note_text = "💡 Tip: Enable both 'Start with Windows' AND 'Start Auto-Sync' for automatic background uploads"
ttk.Label(main_frame, text=note_text, font=('Arial', 8, 'italic'), foreground='#0066cc', wraplength=600).grid(row=15, column=0, columnspan=3, sticky=tk.W, pady=(0, 5))
# Start with Windows checkbox
self.start_with_windows = tk.BooleanVar()
ttk.Checkbutton(main_frame, text="Start with Windows (run in background at startup)", variable=self.start_with_windows, command=self.toggle_autostart).grid(row=16, column=0, columnspan=3, sticky=tk.W, pady=5)
# Check interval
interval_frame = ttk.Frame(main_frame)
interval_frame.grid(row=17, column=0, columnspan=3, sticky=tk.W, pady=5)
ttk.Label(interval_frame, text="Check for new activities every:").pack(side=tk.LEFT, padx=(0, 5))
self.interval_var = tk.IntVar(value=5)
interval_spinbox = ttk.Spinbox(interval_frame, from_=1, to=30, textvariable=self.interval_var, width=5, command=self.mark_settings_changed)
interval_spinbox.pack(side=tk.LEFT)
ttk.Label(interval_frame, text="minutes").pack(side=tk.LEFT, padx=(5, 0))
# Separator
ttk.Separator(main_frame, orient='horizontal').grid(row=18, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10)
# Primary action buttons
btn_frame = ttk.Frame(main_frame)
btn_frame.grid(row=19, column=0, columnspan=3, pady=(4, 2))
ttk.Button(btn_frame, text="Save Settings", command=self.save_settings).pack(side='left', padx=3)
self.sync_button = ttk.Button(btn_frame, text="Sync Now", command=self.sync_now)
self.sync_button.pack(side='left', padx=3)
self.monitor_button = ttk.Button(btn_frame, text="Start Auto-Sync", command=self.toggle_monitoring)
self.monitor_button.pack(side='left', padx=3)
self.minimize_button = ttk.Button(btn_frame, text="Minimize to Tray", command=self.minimize_to_tray)
self.minimize_button.pack(side='left', padx=3)
# Secondary action row
about_frame = ttk.Frame(main_frame)
about_frame.grid(row=20, column=0, columnspan=3, pady=(0, 6))
ttk.Button(about_frame, text="About & update", command=self.show_about).pack()
# Status
self.status_label = ttk.Label(main_frame, text="Status: Idle", foreground='blue', font=('Arial', 9))
self.status_label.grid(row=21, column=0, columnspan=3, pady=(6, 0))
# Last sync time
self.last_sync_label = ttk.Label(main_frame, text="Last sync: Never", foreground='gray', font=('Arial', 8))
self.last_sync_label.grid(row=22, column=0, columnspan=3)
# Last upload info
self.last_upload_label = ttk.Label(main_frame, text="Last upload: None", foreground='gray', font=('Arial', 8))
self.last_upload_label.grid(row=23, column=0, columnspan=3)
# View full log link
log_link = ttk.Label(
main_frame,
text="View Full Log",
foreground='blue',
cursor='hand2',
font=('Arial', 8, 'underline')
)
log_link.grid(row=24, column=0, columnspan=3, pady=(5, 10))
log_link.bind("<Button-1>", lambda e: self.open_log_file())
# Auto-size window to content after UI is built
self._auto_size_to_content()
def update_app_sections(self):
"""Show/hide app folder sections based on expanded state only.
Default is headers only (collapsed). When an app is expanded, its body is
shown and the arrow icon points down; otherwise the body is hidden and
the arrow points right.
"""
# Wahoo
if getattr(self, 'wahoo_expanded', None):
if self.wahoo_expanded.get():
self.wahoo_body.pack(fill='x', padx=(24, 0), pady=(0, 4))
self.wahoo_toggle.config(text="▼")
else:
self.wahoo_body.pack_forget()
self.wahoo_toggle.config(text="▶")
# MyWhoosh
if getattr(self, 'mywhoosh_expanded', None):
if self.mywhoosh_expanded.get():
self.mywhoosh_body.pack(fill='x', padx=(24, 0), pady=(0, 4))
self.mywhoosh_toggle.config(text="▼")
else:
self.mywhoosh_body.pack_forget()
self.mywhoosh_toggle.config(text="▶")
# TrainerDay
if getattr(self, 'trainerday_expanded', None):
if self.trainerday_expanded.get():
self.trainerday_body.pack(fill='x', padx=(24, 0), pady=(0, 4))
self.trainerday_toggle.config(text="▼")
else:
self.trainerday_body.pack_forget()
self.trainerday_toggle.config(text="▶")
self._update_app_status_icons()
# Adjust window height when sections are expanded/collapsed
self._auto_size_to_content()
def _auto_size_to_content(self):
"""Auto-size the main window height to fit current content.
Uses the requested height of the main frame, capped at _max_height,
and preserves scroll position. This keeps the window from leaving
a large empty area when sections are collapsed.
"""
try:
if not hasattr(self, "_main_frame") or not hasattr(self, "_canvas"):
return
canvas = self._canvas
main_frame = self._main_frame
# Force layout calculation
self.root.update_idletasks()
required_height = main_frame.winfo_reqheight() + 40 # Add padding
actual_height = min(required_height, self._max_height)
# Get current geometry width/height
current_width = self.root.winfo_width()
# Capture scroll position before resize
try:
current_pos = canvas.yview()