-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
505 lines (413 loc) · 16.7 KB
/
Copy pathmain.py
File metadata and controls
505 lines (413 loc) · 16.7 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
"""
GitPulse — Main Application Entry Point
Initializes the CustomTkinter application, manages authentication flow,
page navigation, status bar, and orchestrates all subsystems.
"""
import sys
import os
# Add src to path so imports work correctly
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src'))
import threading
import webbrowser
import customtkinter as ctk
from config import (
WINDOW_WIDTH, WINDOW_HEIGHT, COLOR_BG, COLOR_SURFACE,
COLOR_BORDER, COLOR_TEXT, COLOR_TEXT_SECONDARY, COLOR_ACCENT,
COLOR_ACCENT_HOVER, FONT_TITLE, FONT_HEADING, FONT_BODY,
FONT_SMALL, APP_NAME, APP_VERSION,
config,
)
from auth import DeviceFlowAuth
from github_api import GitHubAPI
from database import db
from commit_engine import CommitEngine
from scheduler import CommitScheduler
from tray import TrayManager
from ui.sidebar import Sidebar
from ui.dashboard import DashboardPage
from ui.repos_page import ReposPage
from ui.scheduler_page import SchedulerPage
from ui.languages_page import LanguagesPage
from ui.settings_page import SettingsPage
from ui.manual_commit_page import ManualCommitPage
class GitPulseApp(ctk.CTk):
"""Main GitPulse application window."""
def __init__(self):
"""Initialize the GitPulse application."""
super().__init__()
# Window config
self.title(f"{APP_NAME} v{APP_VERSION}")
self.geometry(f"{WINDOW_WIDTH}x{WINDOW_HEIGHT}")
self.minsize(WINDOW_WIDTH, WINDOW_HEIGHT)
self.resizable(True, True)
self.configure(fg_color=COLOR_BG)
# Set app icon if available
icon_path = self._get_asset_path("icon.ico")
if icon_path and os.path.exists(icon_path):
self.iconbitmap(icon_path)
# Theme
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("dark-blue")
# State
self._github_api = None
self._commit_engine = None
self._scheduler = None
self._tray = None
self._auth = DeviceFlowAuth()
self._pages = {}
self._current_page = None
self._force_quit_flag = False
# Build UI
self._build_status_bar()
# Check for existing token
token = config.get_token()
if token:
self._set_status("Validating token...")
threading.Thread(target=self._validate_and_launch, args=(token,), daemon=True).start()
else:
self._show_login()
# Window close handler
self.protocol("WM_DELETE_WINDOW", self._on_close)
def _get_asset_path(self, filename):
"""
Get the path to an asset file, handling both dev and PyInstaller modes.
Args:
filename: Asset filename
Returns:
Full path to the asset or None
"""
if getattr(sys, 'frozen', False):
base = sys._MEIPASS
else:
base = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(base, "src", "assets", filename)
if not os.path.exists(path):
# Fallback for frozen/built mode if path differs
path = os.path.join(base, "assets", filename)
if os.path.exists(path):
return path
return None
def _build_status_bar(self):
"""Build the bottom status bar."""
self._status_bar = ctk.CTkFrame(
self, height=28, fg_color=COLOR_SURFACE,
corner_radius=0, border_width=0,
)
self._status_bar.pack(side="bottom", fill="x")
self._status_bar.pack_propagate(False)
self._status_label = ctk.CTkLabel(
self._status_bar, text="● Idle",
font=("Segoe UI", 11), text_color=COLOR_TEXT_SECONDARY,
)
self._status_label.pack(side="left", padx=12)
self._rate_label = ctk.CTkLabel(
self._status_bar, text="",
font=("Segoe UI", 10), text_color=COLOR_TEXT_SECONDARY,
)
self._rate_label.pack(side="right", padx=12)
def _set_status(self, text, color=None):
"""
Update the status bar text.
Args:
text: Status message
color: Optional text color
"""
self._status_label.configure(text=f"● {text}")
if color:
self._status_label.configure(text_color=color)
else:
self._status_label.configure(text_color=COLOR_TEXT_SECONDARY)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# LOGIN SCREEN
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def _show_login(self):
"""Display the login screen."""
self._clear_main_content()
self._login_frame = ctk.CTkFrame(self, fg_color=COLOR_BG)
self._login_frame.pack(fill="both", expand=True)
# Center container
center = ctk.CTkFrame(self._login_frame, fg_color="transparent")
center.place(relx=0.5, rely=0.45, anchor="center")
# App logo
ctk.CTkLabel(
center, text="⚡", font=("Segoe UI", 56),
text_color=COLOR_ACCENT,
).pack(pady=(0, 4))
ctk.CTkLabel(
center, text=APP_NAME, font=("Segoe UI", 32, "bold"),
text_color=COLOR_TEXT,
).pack(pady=(0, 4))
ctk.CTkLabel(
center, text="Automated GitHub Contributions", font=FONT_BODY,
text_color=COLOR_TEXT_SECONDARY,
).pack(pady=(0, 32))
# Connect button
self._connect_btn = ctk.CTkButton(
center, text="🔗 Connect with GitHub",
font=("Segoe UI", 14, "bold"), height=44, width=260,
fg_color=COLOR_ACCENT, hover_color=COLOR_ACCENT_HOVER,
text_color="#ffffff", corner_radius=8,
command=self._start_auth,
)
self._connect_btn.pack(pady=(0, 16))
# Loading bar (hidden initially)
self._login_loading = ctk.CTkProgressBar(
center, mode="indeterminate", width=260, height=4,
progress_color=COLOR_ACCENT,
)
# Auth status text
self._auth_status = ctk.CTkLabel(
center, text="", font=FONT_SMALL,
text_color=COLOR_TEXT_SECONDARY,
)
self._auth_status.pack(pady=(0, 8))
# Device code display (hidden initially)
self._code_frame = ctk.CTkFrame(
center, fg_color=COLOR_SURFACE,
corner_radius=8, border_width=1, border_color=COLOR_BORDER,
)
self._set_status("Not connected")
def _start_auth(self):
"""Initiate the GitHub Device Flow authentication."""
self._connect_btn.configure(state="disabled", text="Connecting...")
self._auth_status.configure(text="Requesting device code...")
self._login_loading.pack(pady=(0, 12))
self._login_loading.start()
threading.Thread(target=self._do_auth, daemon=True).start()
def _do_auth(self):
"""Run device flow auth in background."""
result = self._auth.start_device_flow()
if result is None:
self.after(0, lambda: self._auth_failed("Could not connect to GitHub. Check your internet."))
return
user_code = result["user_code"]
device_code = result["device_code"]
interval = result["interval"]
expires_in = result["expires_in"]
verification_uri = result["verification_uri"]
self.after(0, lambda: self._show_device_code(user_code, verification_uri))
self._auth.poll_for_token(
device_code=device_code,
interval=interval,
expires_in=expires_in,
callback=lambda token: self.after(0, lambda: self._auth_success(token)),
error_callback=lambda err: self.after(0, lambda: self._auth_failed(err)),
)
def _show_device_code(self, code, uri):
"""Display the device code to the user."""
self._login_loading.stop()
self._login_loading.pack_forget()
self._connect_btn.pack_forget()
self._code_frame.pack(pady=(0, 16))
for widget in self._code_frame.winfo_children():
widget.destroy()
ctk.CTkLabel(
self._code_frame, text="Enter this code on GitHub:",
font=FONT_SMALL, text_color=COLOR_TEXT_SECONDARY,
).pack(padx=24, pady=(16, 8))
ctk.CTkLabel(
self._code_frame, text=code,
font=("Consolas", 32, "bold"), text_color=COLOR_ACCENT,
).pack(padx=24)
ctk.CTkButton(
self._code_frame, text="🌐 Open GitHub",
font=FONT_BODY, height=36, width=180,
fg_color=COLOR_SURFACE, hover_color="#21262d",
border_width=1, border_color=COLOR_BORDER,
text_color=COLOR_TEXT,
command=lambda: webbrowser.open(uri),
).pack(padx=24, pady=(12, 8))
# Waiting spinner
self._poll_loading = ctk.CTkProgressBar(
self._code_frame, mode="indeterminate", width=200, height=3,
progress_color=COLOR_ACCENT,
)
self._poll_loading.pack(pady=(4, 4))
self._poll_loading.start()
ctk.CTkLabel(
self._code_frame, text="Waiting for authorization...",
font=FONT_SMALL, text_color=COLOR_TEXT_SECONDARY,
).pack(padx=24, pady=(0, 16))
self._auth_status.configure(text="")
self._set_status("Waiting for GitHub authorization...")
def _auth_success(self, token):
"""Handle successful authentication."""
config.set_token(token)
self._set_status("Authenticated!", COLOR_ACCENT)
self._init_app_with_token(token)
def _auth_failed(self, message):
"""Handle failed authentication."""
self._login_loading.stop()
self._login_loading.pack_forget()
self._auth_status.configure(text=message, text_color="#f85149")
self._connect_btn.configure(state="normal", text="🔗 Connect with GitHub")
self._connect_btn.pack(pady=(0, 16))
self._set_status("Authentication failed", "#f85149")
def _validate_and_launch(self, token):
"""Validate existing token and launch the app."""
user_info = DeviceFlowAuth.validate_token(token)
if user_info:
self.after(0, lambda: self._init_app_with_token(token))
else:
config.clear_token()
self.after(0, self._show_login)
self.after(0, lambda: self._set_status("Token expired, please re-authenticate"))
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# MAIN APP (after auth)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def _init_app_with_token(self, token):
"""
Initialize all app subsystems with the given token.
Args:
token: Valid GitHub access token
"""
self._github_api = GitHubAPI(token)
self._commit_engine = CommitEngine(self._github_api, db)
self._scheduler = CommitScheduler(self._commit_engine, self._github_api)
self._scheduler.set_callbacks(
status_callback=lambda msg: self.after(0, lambda: self._set_status(msg)),
commit_callback=lambda result: self.after(0, lambda: self._on_commit_done(result)),
)
# Apply saved schedule
self._scheduler.apply_schedule()
# System tray
self._tray = TrayManager(self, self._commit_engine, self._scheduler)
self._tray.start()
# Show main UI
self._show_main_app()
# Check rate limit
threading.Thread(target=self._check_rate_limit, daemon=True).start()
def _show_main_app(self):
"""Build and display the main application layout."""
self._clear_main_content()
# Main container
self._main_frame = ctk.CTkFrame(self, fg_color=COLOR_BG)
self._main_frame.pack(fill="both", expand=True)
# Sidebar
self._sidebar = Sidebar(self._main_frame, navigate_callback=self._navigate)
self._sidebar.pack(side="left", fill="y")
# Separator line
ctk.CTkFrame(
self._main_frame, width=1, fg_color=COLOR_BORDER,
).pack(side="left", fill="y")
# Page container
self._page_container = ctk.CTkFrame(self._main_frame, fg_color=COLOR_BG)
self._page_container.pack(side="left", fill="both", expand=True)
# App state shared with pages
app_state = {
"github_api": self._github_api,
"database": db,
"scheduler": self._scheduler,
"commit_engine": self._commit_engine,
"logout_callback": self._logout,
"root": self,
}
# Create pages
self._pages = {
"dashboard": DashboardPage(self._page_container, app_state),
"repos": ReposPage(self._page_container, app_state),
"scheduler": SchedulerPage(self._page_container, app_state),
"manual": ManualCommitPage(self._page_container, app_state),
"languages": LanguagesPage(self._page_container, app_state),
"settings": SettingsPage(self._page_container, app_state),
}
# Navigate to dashboard
self._navigate("dashboard")
self._set_status("Idle")
def _navigate(self, page_name):
"""
Navigate to a page by name.
Args:
page_name: Name of the page to display
"""
# Hide current page
if self._current_page and self._current_page in self._pages:
self._pages[self._current_page].pack_forget()
if self._current_page == "dashboard":
self._pages["dashboard"].stop_countdown()
# Show new page
self._current_page = page_name
page = self._pages.get(page_name)
if page:
page.pack(fill="both", expand=True)
self._sidebar.set_active(page_name)
# Refresh data on page show
if page_name == "dashboard":
page.refresh()
elif page_name == "repos" or page_name == "manual":
if hasattr(page, "refresh"):
page.refresh()
elif page_name == "settings":
page.refresh()
def _clear_main_content(self):
"""Clear all content except the status bar."""
for widget in self.winfo_children():
if widget != self._status_bar:
widget.destroy()
self._pages = {}
self._current_page = None
def _on_commit_done(self, result):
"""
Handle commit completion.
Args:
result: Commit result dict
"""
repo = result.get("repo", "unknown")
lang = result.get("language", "unknown")
self._set_status(f"Committed to {repo} in {lang}", COLOR_ACCENT)
# Notify via tray
if self._tray:
self._tray.notify("GitPulse", f"Committed to {repo} in {lang}")
# Refresh dashboard if visible
if self._current_page == "dashboard" and "dashboard" in self._pages:
self._pages["dashboard"]._load_activity()
def _check_rate_limit(self):
"""Check GitHub API rate limit and warn if low."""
if not self._github_api:
return
try:
rate = self._github_api.get_rate_limit()
remaining = rate.get("remaining", 0)
limit = rate.get("limit", 0)
self.after(0, lambda: self._rate_label.configure(
text=f"API: {remaining}/{limit}",
text_color=COLOR_TEXT_SECONDARY if remaining > 100 else "#d29922",
))
except Exception:
pass
def _logout(self):
"""Handle logout: clear token, stop services, show login."""
config.clear_token()
if self._scheduler:
self._scheduler.shutdown()
self._scheduler = None
if self._tray:
self._tray.stop()
self._tray = None
self._github_api = None
self._commit_engine = None
self._show_login()
def _on_close(self):
"""Handle window close button press."""
settings = config.get_settings()
if settings.get("minimize_to_tray", True) and self._tray:
self.withdraw()
else:
self.force_quit()
def force_quit(self):
"""Force quit the application, cleaning up all resources."""
self._force_quit_flag = True
if self._scheduler:
self._scheduler.shutdown()
if self._tray:
self._tray.stop()
if self._auth:
self._auth.cancel_polling()
self.quit()
self.destroy()
def main():
"""Application entry point."""
app = GitPulseApp()
app.mainloop()
if __name__ == "__main__":
main()