-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinget_update_manager.py
More file actions
4650 lines (4170 loc) · 201 KB
/
winget_update_manager.py
File metadata and controls
4650 lines (4170 loc) · 201 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
"""
Winget Update Manager - A Modern GUI wrapper for winget
Full-featured: Dashboard, Installed Apps, Updates, History, Settings.
"""
import subprocess
import threading
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
import sys
import os
import json
import csv
import re
import webbrowser
import ctypes
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
from ctypes import wintypes
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlparse
from urllib.request import Request, urlopen
def get_resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return Path(sys._MEIPASS) / relative_path
return Path(__file__).parent / relative_path
try:
import winreg
except ImportError:
winreg = None
try:
from PIL import Image, ImageDraw, ImageTk
HAS_PIL = True
except ImportError:
HAS_PIL = False
Image = ImageDraw = ImageTk = None
try:
from winotify import Notification as WinNotification
HAS_WINOTIFY = True
except ImportError:
HAS_WINOTIFY = False
try:
import pystray
HAS_TRAY = True
except ImportError:
HAS_TRAY = False
VERSION = "3.0.0"
APP_DIR = Path(os.environ.get("APPDATA", str(Path.home()))) / "WingetUpdateManager"
CONFIG_FILE = APP_DIR / "config.json"
HISTORY_FILE = APP_DIR / "history.json"
CACHE_FILE = APP_DIR / "scan_cache.json"
DARK_COLORS = {
"bg": "#182235",
"surface": "#202b3f",
"surface_alt": "#223149",
"surface_hover": "#2a3954",
"surface_soft": "#1c2638",
"border": "#31415e",
"border_soft": "#293753",
"primary": "#5ea2ff",
"primary_dim": "#447ed2",
"secondary": "#21c087",
"accent": "#8b5cf6",
"text_main": "#f3f7ff",
"text_dim": "#8fa2c3",
"text_soft": "#6f84a8",
"danger": "#ff5d6c",
"warning": "#f4b740",
"console_bg": "#07101f",
"console_header": "#0d1727",
"success": "#2dde98",
"card_bg": "#202b3f",
"card_inner": "#1b2739",
"nav_active": "#2a3b5a",
"nav_badge_bg": "#194e5a",
"nav_badge_fg": "#7df2ba",
}
LIGHT_COLORS = {
"bg": "#eef4fb",
"surface": "#ffffff",
"surface_alt": "#f5f8fc",
"surface_hover": "#eef4fb",
"surface_soft": "#f7f9fd",
"border": "#d7e1ef",
"border_soft": "#e4ebf5",
"primary": "#377dff",
"primary_dim": "#2d64d1",
"secondary": "#19b57d",
"accent": "#8b5cf6",
"text_main": "#142033",
"text_dim": "#5e718e",
"text_soft": "#7d8faa",
"danger": "#e5485d",
"warning": "#ca8a04",
"console_bg": "#0f172a",
"console_header": "#182436",
"success": "#109e69",
"card_bg": "#ffffff",
"card_inner": "#f6f8fc",
"nav_active": "#dfeafb",
"nav_badge_bg": "#ddf7eb",
"nav_badge_fg": "#0f8d61",
}
FONTS = {
"title": ("Segoe UI", 21, "bold"),
"header": ("Segoe UI", 19, "bold"),
"sub_header": ("Segoe UI", 14, "bold"),
"body": ("Segoe UI", 10),
"body_bold": ("Segoe UI", 10, "bold"),
"small": ("Segoe UI", 9),
"small_bold": ("Segoe UI", 9, "bold"),
"micro": ("Segoe UI", 8, "bold"),
"nav": ("Segoe UI", 10, "bold"),
"mono": ("Consolas", 10),
"mono_small": ("Consolas", 9),
}
SPACING = {
"page_x": 28,
"page_y": 24,
"card_gap": 18,
"card_pad": 22,
"control_gap": 10,
"row_pad_y": 14,
}
DEFAULT_CONFIG = {
"theme": "dark",
"auto_check_on_launch": True,
"auto_check_interval_hours": 24,
"excluded_packages": [],
"update_groups": {},
"quiet_mode_packages": [],
"quiet_mode_enabled": False,
"silent_mode": True,
"scheduled_scan": False,
"cache_ttl": 3600,
"parallel_workers": 1,
"start_at_login": False,
"window_geometry": "1100x750",
"minimize_to_tray": False,
}
if os.name == "nt":
class ICONINFO(ctypes.Structure):
_fields_ = [
("fIcon", wintypes.BOOL),
("xHotspot", wintypes.DWORD),
("yHotspot", wintypes.DWORD),
("hbmMask", wintypes.HBITMAP),
("hbmColor", wintypes.HBITMAP),
]
class BITMAP(ctypes.Structure):
_fields_ = [
("bmType", wintypes.LONG),
("bmWidth", wintypes.LONG),
("bmHeight", wintypes.LONG),
("bmWidthBytes", wintypes.LONG),
("bmPlanes", wintypes.WORD),
("bmBitsPixel", wintypes.WORD),
("bmBits", wintypes.LPVOID),
]
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [
("biSize", wintypes.DWORD),
("biWidth", wintypes.LONG),
("biHeight", wintypes.LONG),
("biPlanes", wintypes.WORD),
("biBitCount", wintypes.WORD),
("biCompression", wintypes.DWORD),
("biSizeImage", wintypes.DWORD),
("biXPelsPerMeter", wintypes.LONG),
("biYPelsPerMeter", wintypes.LONG),
("biClrUsed", wintypes.DWORD),
("biClrImportant", wintypes.DWORD),
]
class RGBQUAD(ctypes.Structure):
_fields_ = [
("rgbBlue", ctypes.c_byte),
("rgbGreen", ctypes.c_byte),
("rgbRed", ctypes.c_byte),
("rgbReserved", ctypes.c_byte),
]
class BITMAPINFO(ctypes.Structure):
_fields_ = [
("bmiHeader", BITMAPINFOHEADER),
("bmiColors", RGBQUAD * 1),
]
class Config:
def __init__(self):
APP_DIR.mkdir(parents=True, exist_ok=True)
self.data = DEFAULT_CONFIG.copy()
self.load()
def load(self):
try:
if CONFIG_FILE.exists():
with open(CONFIG_FILE, "r") as f:
saved = json.load(f)
for k, v in saved.items():
if k in self.data:
self.data[k] = v
except Exception:
pass
def save(self):
try:
with open(CONFIG_FILE, "w") as f:
json.dump(self.data, f, indent=2)
except Exception:
pass
def get(self, key, default=None):
return self.data.get(key, default)
def set(self, key, value):
self.data[key] = value
self.save()
class HistoryManager:
def __init__(self):
APP_DIR.mkdir(parents=True, exist_ok=True)
self.entries = []
self.rollback_ledger = {}
self.load()
def load(self):
try:
if HISTORY_FILE.exists():
with open(HISTORY_FILE, "r") as f:
raw = json.load(f)
if isinstance(raw, list):
self.entries = raw
elif isinstance(raw, dict):
self.entries = raw.get("entries", [])
self.rollback_ledger = self._normalize_ledger(raw.get("rollback_ledger", {}))
except Exception:
pass
if not self.rollback_ledger:
self._rebuild_ledger_from_entries()
def save(self):
try:
with open(HISTORY_FILE, "w") as f:
json.dump({"entries": self.entries, "rollback_ledger": self.rollback_ledger}, f, indent=2)
except Exception:
pass
def _normalize_ledger(self, ledger):
if not isinstance(ledger, dict): return {}
normalized = {}
for pkg_id, items in ledger.items():
clean = [{"version": str(i.get("version", "")).strip(),
"manager": i.get("manager", "winget"),
"timestamp": i.get("timestamp", datetime.now().isoformat())}
for i in items if isinstance(i, dict) and str(i.get("version", "")).strip()]
if clean: normalized[str(pkg_id)] = clean[-100:]
return normalized
def _append_ledger_version(self, package_id, version, manager="winget", timestamp=None):
pkg_id, ver = str(package_id or "").strip(), str(version or "").strip()
if not pkg_id or not ver: return
items = self.rollback_ledger.setdefault(pkg_id, [])
entry = {"version": ver, "manager": manager, "timestamp": timestamp or datetime.now().isoformat()}
if not items or items[-1]["version"] != ver:
items.append(entry)
else:
items[-1] = entry
self.rollback_ledger[pkg_id] = items[-100:]
def _rebuild_ledger_from_entries(self):
for entry in reversed(self.entries):
if entry.get("status") == "success" and entry.get("manager", "winget") == "winget":
pkg_id = entry.get("package_id")
for ver_key in ["old_version", "new_version"]:
if entry.get(ver_key):
self._append_ledger_version(pkg_id, entry[ver_key], "winget", entry.get("timestamp"))
def add(self, package_id, package_name, old_ver, new_ver, status, manager="winget"):
self.entries.insert(0, {
"timestamp": datetime.now().isoformat(),
"package_id": package_id,
"package_name": package_name,
"old_version": old_ver,
"new_version": new_ver,
"status": status,
"manager": manager,
})
self.entries = self.entries[:500]
self.save()
def record_version(self, package_id, version, manager="winget", timestamp=None):
if manager == "winget":
self._append_ledger_version(package_id, version, manager, timestamp)
self.save()
def previous_version(self, package_id, current_version, manager="winget"):
if manager != "winget": return None
cur = str(current_version or "").strip()
for item in reversed(self.rollback_ledger.get(package_id, [])):
if item["version"] != cur: return item["version"]
return None
def get_entries(self, limit=100):
return self.entries[:limit]
def clear(self):
self.entries, self.rollback_ledger = [], {}
self.save()
class ScanCache:
def __init__(self):
APP_DIR.mkdir(parents=True, exist_ok=True)
self.data = {"updates": [], "installed": [], "timestamp": None}
self.load()
def load(self):
try:
if CACHE_FILE.exists():
with open(CACHE_FILE, "r") as f:
self.data = json.load(f)
except Exception:
self.data = {"updates": [], "installed": [], "timestamp": None}
def save(self, updates=None, installed=None):
if updates is not None:
self.data["updates"] = updates
if installed is not None:
self.data["installed"] = installed
self.data["timestamp"] = datetime.now().isoformat()
try:
with open(CACHE_FILE, "w") as f:
json.dump(self.data, f, indent=2)
except Exception:
pass
def get_updates(self):
return self.data.get("updates", [])
def get_installed(self):
return self.data.get("installed", [])
def age_seconds(self):
ts = self.data.get("timestamp")
if not ts:
return float("inf")
try:
return (datetime.now() - datetime.fromisoformat(ts)).total_seconds()
except Exception:
return float("inf")
def is_stale(self, ttl=3600):
return self.age_seconds() > ttl
def last_scan_time(self):
ts = self.data.get("timestamp")
if not ts:
return "Never"
try:
return datetime.fromisoformat(ts).strftime("%H:%M")
except Exception:
return "Unknown"
class WingetParser:
@staticmethod
def _parse_tabular_output(output, required_cols):
items = []
lines = output.strip().split("\n")
header_idx = -1
for i, line in enumerate(lines):
if all(col in line for col in required_cols):
header_idx = i
break
if header_idx == -1:
return []
header = lines[header_idx]
cols = {col.lower(): header.find(col) for col in ["Name", "Id", "Version", "Available", "Source"] if header.find(col) >= 0}
sorted_cols = sorted(cols.items(), key=lambda x: x[1])
for line in lines[header_idx + 1:]:
if not line.strip() or line.strip().startswith("-") or "upgrades available" in line.lower():
continue
if len(line) < max(cols.values()):
continue
try:
parts = {}
for j, (name, start) in enumerate(sorted_cols):
end = sorted_cols[j + 1][1] if j + 1 < len(sorted_cols) else len(line)
parts[name] = line[start:end].strip()
if all(parts.get(col.lower()) for col in required_cols):
items.append(parts)
except Exception:
continue
return items
@staticmethod
def parse_upgrade_output(output):
raw_items = WingetParser._parse_tabular_output(output, ["Name", "Id", "Version", "Available"])
return [
{
"name": item["name"],
"id": item["id"],
"version": item["version"],
"available": item["available"],
"manager": "winget",
}
for item in raw_items if item["available"] != item["version"]
]
@staticmethod
def parse_list_output(output):
raw_items = WingetParser._parse_tabular_output(output, ["Name", "Id"])
return [
{
"name": item["name"],
"id": item["id"],
"version": item.get("version", ""),
"source": item.get("source", ""),
"manager": "winget",
}
for item in raw_items
]
class ScrollableFrame(tk.Frame):
def __init__(self, parent, bg_color, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, bg=bg_color)
self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.scrollable_frame = tk.Frame(self.canvas, bg=bg_color)
self.bg_color = bg_color
self.scrollable_frame.bind("<Configure>", self._on_frame_configure)
self.window_id = self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.pack(side="left", fill="both", expand=True)
self.scrollbar.pack(side="right", fill="y")
self.canvas.bind("<Enter>", self._bind_mousewheel)
self.canvas.bind("<Leave>", self._unbind_mousewheel)
self.canvas.bind("<Configure>", self._on_canvas_configure)
def _on_frame_configure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _on_canvas_configure(self, event):
self.canvas.itemconfig(self.window_id, width=event.width)
def _bind_mousewheel(self, event):
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbind_mousewheel(self, event):
self.canvas.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
class Toast:
_notifications = []
_change_callback = None
def __init__(self, root, message, type_="info", duration=3000, record=True):
colors = {
"info": "#3b82f6", "success": "#10b981",
"error": "#ef4444", "warning": "#f59e0b",
}
if record:
Toast._notifications.insert(0, {
"message": message, "type": type_,
"timestamp": datetime.now().strftime("%H:%M:%S"),
})
Toast._notifications = Toast._notifications[:50]
if callable(Toast._change_callback):
try:
root.after(0, Toast._change_callback)
except Exception:
pass
bg = colors.get(type_, "#3b82f6")
self.top = tk.Toplevel(root)
self.top.overrideredirect(True)
self.top.attributes('-topmost', True)
frame = tk.Frame(self.top, bg=bg, padx=20, pady=12)
frame.pack(fill=tk.BOTH, expand=True)
tk.Label(frame, text=message, bg=bg, fg="white",
font=("Segoe UI", 10, "bold")).pack()
root.update_idletasks()
rx = root.winfo_rootx() + root.winfo_width() - 320
ry = root.winfo_rooty() + 10
self.top.geometry(f"300x44+{rx}+{ry}")
self.top.after(duration, self._dismiss)
def _dismiss(self):
try:
self.top.destroy()
except Exception:
pass
class WingetUpdateManager:
def __init__(self, root):
self.root = root
self.config = Config()
self.history = HistoryManager()
self.scan_cache = ScanCache()
self.parser = WingetParser()
self.scan_only_mode = "--scan-only" in sys.argv
self.minimized_mode = "--minimized" in sys.argv
self.root.title("Winget Update Manager")
icon_path = get_resource_path("assets/icon.png")
if HAS_PIL and icon_path.exists():
try:
img = Image.open(str(icon_path)).convert("RGBA")
self.app_icon = ImageTk.PhotoImage(img)
self.root.iconphoto(True, self.app_icon)
except Exception:
pass
geo = self.config.get("window_geometry", "1100x750")
self.root.geometry(geo)
self.root.minsize(1120, 720)
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.current_page = "updates"
self.updates_list = []
self.installed_list = []
self.checkboxes = {}
self.is_checking = False
self.is_updating = False
self.all_selected_var = False
self.sort_column = None
self.sort_ascending = True
self.search_var = tk.StringVar()
self.installed_search_var = tk.StringVar()
self.group_filter_var = tk.StringVar(value="All Packages")
self.active_process = None
self.active_processes = set()
self.active_process_lock = threading.Lock()
self.cancel_requested = threading.Event()
self.update_count = 0
self.tray_icon = None
self.console_frame = None
self.console_idle_height = 168
self.console_active_height = 238
self.console_anim_job = None
self.pages = {}
self.nav_items = {}
self.nav_accents = {}
self.header_dividers = {}
self.registry_app_index = None
self.registry_apps_by_name = {}
self.package_icon_refs = {}
self.tk_icon_cache = {}
self.brand_photo = None
self.focused_row_index = -1
self.row_widgets = []
self.notifications = Toast._notifications
self.notification_badges = []
self.discover_busy = False
self.discover_action_var = tk.StringVar(value="Idle")
self.selected_group_name = None
self.colors = DARK_COLORS if self.config.get("theme") == "dark" else LIGHT_COLORS
self.root.configure(bg=self.colors["bg"])
Toast._change_callback = self._refresh_notification_indicators
self.setup_styles()
self.setup_ui()
self.bind_shortcuts()
if self.config.get("auto_check_on_launch") and not self.scan_only_mode:
self.root.after(500, self.check_updates)
self.root.after(100, self.verify_winget)
self._load_from_cache()
def _load_from_cache(self):
cached_updates = self.scan_cache.get_updates()
cached_installed = self.scan_cache.get_installed()
if cached_updates:
self.updates_list = cached_updates
for pkg in self.updates_list:
pkg["icon_ref"] = self._get_package_icon_ref(pkg) if hasattr(self, '_get_package_icon_ref') else None
self.root.after(200, self._render_updates)
if cached_installed:
self.installed_list = cached_installed
self.root.after(300, self._render_installed)
def verify_winget(self):
def check():
try:
result = subprocess.run(
["winget", "--version"],
capture_output=True, text=True, timeout=10,
creationflags=subprocess.CREATE_NO_WINDOW
)
if result.returncode != 0:
raise Exception("winget returned non-zero")
except FileNotFoundError:
self.root.after(0, self._show_winget_missing)
except Exception:
pass
threading.Thread(target=check, daemon=True).start()
def _show_winget_missing(self):
messagebox.showwarning(
"Winget Not Found",
"winget is not installed or not in PATH.\n\n"
"Install it from the Microsoft Store (App Installer)\n"
"or visit: https://github.com/microsoft/winget-cli"
)
def setup_styles(self):
style = ttk.Style()
style.theme_use('clam')
style.configure("Vertical.TScrollbar",
gripcount=0,
background=self.colors["surface_hover"],
darkcolor=self.colors["surface_soft"],
lightcolor=self.colors["surface_hover"],
troughcolor=self.colors["card_bg"],
bordercolor=self.colors["card_bg"],
arrowcolor=self.colors["text_dim"]
)
def setup_ui(self):
self.sidebar = tk.Frame(self.root, bg=self.colors["surface_soft"], width=260)
self.sidebar.pack(side=tk.LEFT, fill=tk.Y)
self.sidebar.pack_propagate(False)
self._build_sidebar()
self.info_panel = tk.Frame(self.root, bg=self.colors["surface"], width=0,
highlightthickness=1,
highlightbackground=self.colors["border"])
self.info_panel.pack_propagate(False)
self._build_info_panel()
self.main_container = tk.Frame(self.root, bg=self.colors["bg"])
self.main_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self._build_dashboard_page()
self._build_installed_page()
self._build_updates_page()
self._build_discover_page()
self._build_history_page()
self._build_settings_page()
self.switch_page("updates")
# ------------------------------------------------------------------ sidebar
def _build_sidebar(self):
brand_bg = self.colors["surface_soft"]
brand = tk.Frame(self.sidebar, bg=brand_bg, padx=18, pady=20)
brand.pack(fill=tk.X)
icon_wrap = tk.Frame(brand, bg=brand_bg, width=48, height=48)
icon_wrap.pack(side=tk.LEFT)
icon_wrap.pack_propagate(False)
img_path = get_resource_path("assets/icon.png")
if img_path.exists() and HAS_PIL:
try:
img = Image.open(str(img_path)).convert("RGBA")
img = img.resize((48, 48), Image.LANCZOS)
self.brand_photo = ImageTk.PhotoImage(img, master=self.root)
tk.Label(icon_wrap, image=self.brand_photo, borderwidth=0, bg=brand_bg).pack(expand=True)
except Exception:
tk.Label(icon_wrap, text="\u25B7_", bg=self.colors["primary"],
fg="white", font=("Segoe UI", 14, "bold")).pack(expand=True)
else:
tk.Label(icon_wrap, text="\u25B7_", bg=self.colors["primary"],
fg="white", font=("Segoe UI", 14, "bold")).pack(expand=True)
brand_text = tk.Frame(brand, bg=brand_bg)
brand_text.pack(side=tk.LEFT, padx=(12, 0))
tk.Label(brand_text, text="Winget UM", bg=brand_bg,
fg=self.colors["text_main"], font=("Segoe UI", 18, "bold")).pack(anchor="w")
tk.Label(brand_text, text="Update workspace", bg=brand_bg,
fg=self.colors["primary"], font=FONTS["small"]).pack(anchor="w")
nav = tk.Frame(self.sidebar, bg=self.colors["surface_soft"], padx=14, pady=8)
nav.pack(fill=tk.BOTH, expand=True)
for pid, label, icon in [
("dashboard", "Dashboard", "\u25A6"),
("installed", "Installed Apps", "\u25A4"),
("updates", "Updates", "\u27F3"),
("discover", "Discover", "\U0001F50D"),
("history", "History", "\u29D7"),
]:
self._build_nav_item(nav, pid, label, icon)
bottom = tk.Frame(self.sidebar, bg=self.colors["surface_soft"], padx=14, pady=12)
bottom.pack(side=tk.BOTTOM, fill=tk.X)
self._build_nav_item(bottom, "settings", "Settings", "\u2699")
ver = tk.Frame(bottom, bg=self.colors["surface"], padx=14, pady=8,
highlightthickness=1,
highlightbackground=self.colors["border_soft"])
ver.pack(fill=tk.X, pady=(12, 2))
tk.Label(ver, text=f"\u25CF v{VERSION} stable", bg=self.colors["surface"],
fg=self.colors["text_soft"], font=("Consolas", 8)).pack(anchor="w")
def _build_info_panel(self):
header = tk.Frame(self.info_panel, bg=self.colors["surface_alt"], pady=18, padx=18)
header.pack(fill=tk.X)
self.info_title = tk.Label(header, text="Package Details", bg=self.colors["surface_alt"],
fg=self.colors["text_main"], font=FONTS["sub_header"])
self.info_title.pack(side=tk.LEFT)
close_btn = tk.Label(header, text="\u2715", bg=self.colors["surface_alt"],
fg=self.colors["text_dim"], font=("Segoe UI", 12), cursor="hand2")
close_btn.pack(side=tk.RIGHT)
close_btn.bind("<Button-1>", lambda e: self.hide_info_panel())
sc = ScrollableFrame(self.info_panel, bg_color=self.colors["surface"])
sc.pack(fill=tk.BOTH, expand=True)
self.info_content = sc.scrollable_frame
self.info_msg = tk.Label(self.info_content, text="", bg=self.colors["surface"],
fg=self.colors["text_dim"], font=FONTS["body"])
self.info_msg.pack(pady=20)
self.info_labels = {}
for key in ["Description", "Homepage", "License", "Installer Type", "Publisher",
"Install Date", "Size", "Tags"]:
f = tk.Frame(self.info_content, bg=self.colors["surface"], pady=5)
f.pack(fill=tk.X, padx=18)
tk.Label(f, text=key.upper(), bg=self.colors["surface"], fg=self.colors["text_soft"],
font=FONTS["micro"]).pack(anchor="w")
lbl = tk.Label(f, text="---", bg=self.colors["surface"], fg=self.colors["text_main"],
font=FONTS["body"], wraplength=250, justify="left")
lbl.pack(anchor="w")
self.info_labels[key] = lbl
btn_frame = tk.Frame(self.info_content, bg=self.colors["surface"], pady=12)
btn_frame.pack(fill=tk.X, padx=18)
self.info_homepage_btn = self._btn(btn_frame, "\U0001F310 Visit Homepage",
self.colors["primary"], "white",
lambda: self._open_info_homepage())
self.info_homepage_btn.pack(fill=tk.X, pady=(0, 6))
self.info_changelog_btn = self._btn(
btn_frame, "\U0001F4DD View Changelog", self.colors["surface_alt"],
self.colors["text_main"], lambda: self._open_info_changelog(), outline=True
)
self.info_changelog_btn.pack(fill=tk.X, pady=(0, 6))
self.info_uninstall_btn = self._btn(btn_frame, "\U0001F5D1 Uninstall",
self.colors["danger"], "white",
lambda: self._uninstall_info_package())
self.info_uninstall_btn.pack(fill=tk.X)
self._info_current_pkg = None
self._info_homepage_url = None
self._info_release_notes_url = None
def show_info_panel(self, pkg_id, pkg_name, manager="winget"):
if not self.info_panel.winfo_ismapped():
self.info_panel.pack(side=tk.RIGHT, fill=tk.Y, before=self.main_container)
self._animate_panel_width(self.info_panel, 330)
self.info_title.config(text=pkg_name)
self.info_msg.config(text="Fetching details...")
for lbl in self.info_labels.values():
lbl.config(text="---")
current_pkg = self._find_installed_package(pkg_id, manager)
if not current_pkg:
current_pkg = next(
(pkg for pkg in self.updates_list if pkg.get("id") == pkg_id and pkg.get("manager", "winget") == manager),
None,
)
self._info_current_pkg = {
"id": pkg_id,
"name": pkg_name,
"manager": manager,
"version": (current_pkg or {}).get("version", ""),
}
self._info_homepage_url = None
self._info_release_notes_url = None
self.info_homepage_btn.config(state=tk.DISABLED)
self.info_changelog_btn.config(state=tk.DISABLED, bg=self.colors["surface_alt"])
def fetch():
try:
if manager == "npm":
proc = subprocess.run(
[self._npm_command(), "view", pkg_id, "--json"],
capture_output=True, text=True, encoding='utf-8',
errors='ignore', creationflags=subprocess.CREATE_NO_WINDOW
)
if proc.returncode == 0:
raw = json.loads(proc.stdout or "{}")
publisher = raw.get("author")
if isinstance(publisher, dict):
publisher = publisher.get("name") or publisher.get("email")
if not publisher:
maintainers = raw.get("maintainers")
if isinstance(maintainers, list) and maintainers:
publisher = maintainers[0]
if isinstance(publisher, str):
publisher = publisher.split("<", 1)[0].strip()
homepage = raw.get("homepage")
if not homepage:
repo = raw.get("repository")
if isinstance(repo, dict):
homepage = repo.get("url")
elif isinstance(repo, str):
homepage = repo
data = {
"Description": raw.get("description") or "---",
"Homepage": homepage or "---",
"License": raw.get("license") or "---",
"Installer Type": "npm global package",
"Publisher": publisher or "npm registry",
"_release_notes_url": None,
}
self.root.after(0, lambda: self._update_info_panel(data))
else:
self.root.after(0, lambda: self.info_msg.config(text="Failed to fetch npm details."))
else:
proc = subprocess.run(
["winget", "show", "--id", pkg_id, "--exact", "--accept-source-agreements"],
capture_output=True, text=True, encoding='utf-8',
errors='ignore', creationflags=subprocess.CREATE_NO_WINDOW
)
if proc.returncode == 0:
data = self._parse_labelled_output(proc.stdout)
registry = self._match_registry_record(self._info_current_pkg)
if registry:
data.setdefault("Publisher", registry.get("publisher") or "---")
if registry.get("install_date") and not data.get("Install Date"):
data["Install Date"] = registry["install_date"]
if registry.get("estimated_size") and not data.get("Size"):
data["Size"] = registry["estimated_size"]
data["_release_notes_url"] = (
data.get("Release Notes Url")
or data.get("Release Notes URL")
or data.get("Release Notes")
)
self.root.after(0, lambda: self._update_info_panel(data))
else:
self.root.after(0, lambda: self.info_msg.config(text="Failed to fetch details."))
except Exception:
self.root.after(0, lambda: self.info_msg.config(text="Error fetching details."))
threading.Thread(target=fetch, daemon=True).start()
def _update_info_panel(self, data):
self.info_msg.config(text="")
mapping = {
"Description": ["Description", "Short Description"],
"Homepage": ["Homepage", "Publisher Url", "Author Url"],
"License": ["License"],
"Installer Type": ["Installer Type", "Installer"],
"Publisher": ["Publisher"],
"Install Date": ["Install Date", "InstallDate"],
"Size": ["Size", "Installer Size", "Download Size"],
"Tags": ["Tags", "Moniker"],
}
for ui_key, source_keys in mapping.items():
for sk in source_keys:
if sk in data and data[sk] and data[sk] != "---":
self.info_labels[ui_key].config(text=str(data[sk]))
break
hp = data.get("Homepage") or data.get("Publisher Url") or data.get("Author Url")
self._info_homepage_url = hp if hp and hp != "---" else None
self._info_release_notes_url = data.get("_release_notes_url") or None
self.info_homepage_btn.config(state=tk.NORMAL if self._info_homepage_url else tk.DISABLED)
changelog_supported = (
self._info_current_pkg
and self._info_current_pkg.get("manager", "winget") == "winget"
and bool(self._info_release_notes_url)
)
self.info_changelog_btn.config(
state=tk.NORMAL if changelog_supported else tk.DISABLED,
bg=self.colors["primary"] if changelog_supported else self.colors["surface_alt"],
)
def _open_info_homepage(self):
if self._info_homepage_url:
webbrowser.open(self._info_homepage_url)
def _open_info_changelog(self):
if self._info_current_pkg:
self._show_changelog_for_package(self._info_current_pkg, self._info_release_notes_url)
def _uninstall_info_package(self):
if not self._info_current_pkg:
return
pkg = self._info_current_pkg
if not messagebox.askyesno("Uninstall", f"Uninstall {pkg.get('name', pkg.get('id'))}?"):
return
manager = pkg.get("manager", "winget")
def do_uninstall():
try:
if manager == "npm":
cmd = [self._npm_command(), "uninstall", "-g", pkg["id"]]
else:
cmd = ["winget", "uninstall", "--id", pkg["id"], "--exact",
"--accept-source-agreements", "--disable-interactivity"]
proc = subprocess.run(
cmd, capture_output=True, text=True, timeout=120,
creationflags=subprocess.CREATE_NO_WINDOW
)
if proc.returncode != 0:
raise RuntimeError(self._tail_message(
proc.stderr or proc.stdout,
f"Exit code {proc.returncode}",
))
self.root.after(0, lambda: Toast(self.root, f"Uninstalled {pkg['id']}", "success"))
self.root.after(200, self.load_installed)
self.root.after(200, self.check_updates)
except Exception as e:
self.root.after(0, lambda: Toast(self.root, f"Uninstall failed: {e}", "error"))
threading.Thread(target=do_uninstall, daemon=True).start()
def _show_changelog_for_package(self, pkg, release_notes_url=None):
if not pkg or pkg.get("manager", "winget") != "winget":
Toast(self.root, "Changelog is only supported for winget packages", "info")
return
url = release_notes_url or ""
if not url:
try:
proc = self._run_winget_capture(
["show", "--id", pkg.get("id", ""), "--exact", "--accept-source-agreements"],
timeout=60,
)
if proc.returncode == 0:
data = self._parse_labelled_output(proc.stdout)
url = (
data.get("Release Notes Url")
or data.get("Release Notes URL")
or data.get("Release Notes")
or ""
)
except Exception:
url = ""
if not url:
Toast(self.root, "No changelog URL is available for this package", "warning")
return
repo = self._github_repo_from_url(url)
if not repo:
webbrowser.open(url)
return
owner, name = repo
popup = tk.Toplevel(self.root)
popup.title(f"Changelog - {pkg.get('name', pkg.get('id', 'Package'))}")
popup.geometry("760x560")
popup.configure(bg=self.colors["bg"])
header = tk.Frame(popup, bg=self.colors["surface"], padx=18, pady=12)
header.pack(fill=tk.X)
tk.Label(
header, text=f"{pkg.get('name', pkg.get('id', 'Package'))} changelog",
bg=self.colors["surface"], fg=self.colors["text_main"], font=FONTS["sub_header"]
).pack(side=tk.LEFT)
self._btn(
header, "Open in Browser", self.colors["surface_alt"], self.colors["text_main"],
lambda: webbrowser.open(url), outline=True
).pack(side=tk.RIGHT)
body = scrolledtext.ScrolledText(
popup, bg=self.colors["card_bg"], fg=self.colors["text_main"],
font=FONTS["body"], relief=tk.FLAT, wrap=tk.WORD, padx=16, pady=16
)
body.pack(fill=tk.BOTH, expand=True, padx=18, pady=(0, 18))
body.insert(tk.END, "Loading latest GitHub release notes...")
body.config(state=tk.DISABLED)
def load_notes():
try: