-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPYLibrariesList_V2.5+ FINALE+++ patch4.py
More file actions
2464 lines (2031 loc) · 115 KB
/
PYLibrariesList_V2.5+ FINALE+++ patch4.py
File metadata and controls
2464 lines (2031 loc) · 115 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
"""
PYLibrariesList V2.5+ (FINALE+++): A high-performance Python package manager.
This major update introduces support for the 'uv' backend for massive speed
gains, adds a new 'Tools' tab with professional features (orphaned package
finder, requirements compiler), and integrates virtual environment management.
Dependencies are now optional for easier setup, and stability is enhanced
by ensuring background tasks terminate correctly.
patch2 adds advanced venv creation: specify a Python version (uv-only) and
pre-install packages right from the creation dialog.
patch3 (Refactor, Robustness & Security): The codebase is refactored into logical
helper classes. Adds tools to find/fix corrupted packages and scan for known
vulnerabilities using pip-audit. Introduces a self-restart mechanism for safely
uninstalling in-use packages.
patch4 adds new "force reinstall" checkbox to Install Packages tab, improved "Damaged Packages" tool and reliability of initial packet scanning.
"""
# === Imports ===
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import os
import subprocess
import sys
import datetime
import queue
import json
import webbrowser
import threading
import importlib.metadata
import re
from collections import defaultdict, namedtuple
import hashlib
import shutil
# === Optional Imports ===
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
DND_AVAILABLE = True
except ImportError:
DND_AVAILABLE = False
try:
from packaging.version import parse as parse_version, InvalidVersion
PACKAGING_AVAILABLE = True
except ImportError:
PACKAGING_AVAILABLE = False
try:
import tomli
TOMLI_AVAILABLE = True
except ImportError:
TOMLI_AVAILABLE = False
# === Constants & NamedTuples ===
CACHE_FILE_TEMPLATE = os.path.join(os.path.expanduser("~"), ".pylibs_manager_cache_{env_hash}.json")
SETTINGS_FILE = os.path.join(os.path.expanduser("~"), ".pylibs_manager_settings.json")
CACHE_VERSION = 4
APP_VERSION = "2.5+ FINALE+++ patch4"
BUILD_NUMBER = "2025.07.06"
VenvConfig = namedtuple("VenvConfig", ["path", "python_version", "packages"])
# === Utils ===
class PackageUtils:
"""A collection of static utility functions for handling package data."""
@staticmethod
def format_size(num_bytes):
"""Converts bytes to a human-readable string (KB, MB, GB)."""
if num_bytes is None or num_bytes < 1: return "N/A"
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if num_bytes < 1024.0: return f"{num_bytes:.2f} {unit}"
num_bytes /= 1024.0
return f"{num_bytes:.2f} PB"
@staticmethod
def format_date(date_obj):
"""Formats a datetime object into a YYYY-MM-DD string."""
if date_obj is None: return "unknown"
return date_obj.strftime("%Y-%m-%d")
@staticmethod
def get_package_info_modern(dist: importlib.metadata.Distribution):
"""Gathers detailed information for a single package using importlib.metadata."""
name = dist.metadata.get("Name", "N/A")
version = dist.version
size, install_date_ts, location = 0, None, ""
try:
if dist.files:
size = sum(f.size for f in dist.files if f.size is not None)
if hasattr(dist, '_path') and dist._path and os.path.exists(dist._path):
location = str(dist._path)
install_date_ts = os.path.getmtime(location)
else:
path_to_metadata = dist.locate_file('')
if path_to_metadata:
location = str(path_to_metadata.parent)
install_date_ts = os.path.getmtime(location)
except Exception:
pass
installer = "unknown"
try:
installer_file_content = dist.read_text('INSTALLER')
if installer_file_content:
installer = installer_file_content.strip()
except (FileNotFoundError, TypeError, AttributeError):
pass
return {
"name": name,
"version": version,
"size": size,
"install_date_ts": install_date_ts,
"location": location,
"installer": installer,
"metadata": {k: v for k, v in dist.metadata.items()},
"requires": dist.requires or []
}
@staticmethod
def get_version_sort_key(version_string):
"""Extracts the first version from a string and parses it for proper sorting."""
base_version_str = version_string.split("→")[0].strip()
if PACKAGING_AVAILABLE:
try:
return parse_version(base_version_str)
except InvalidVersion:
return parse_version("0.0.0")
else:
return base_version_str
# === GUI Helpers ===
class Tooltip:
"""Creates a tooltip for a given widget."""
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip_window = None
self.widget.bind("<Enter>", self.show_tooltip)
self.widget.bind("<Leave>", self.hide_tooltip)
def show_tooltip(self, event):
x = event.x_root + 10
y = event.y_root + 10
self.tooltip_window = tk.Toplevel(self.widget)
self.tooltip_window.wm_overrideredirect(True)
self.tooltip_window.wm_geometry(f"+{x}+{y}")
label = tk.Label(self.tooltip_window, text=self.text, justify='left',
background="#ffffe0", relief='solid', borderwidth=1,
font=("tahoma", "8", "normal"))
label.pack(ipadx=1)
def hide_tooltip(self, event):
if self.tooltip_window:
self.tooltip_window.destroy()
self.tooltip_window = None
class CreateVenvDialog(tk.Toplevel):
"""A dialog for configuring and creating a new virtual environment."""
def __init__(self, parent, package_manager, current_interpreter_path):
super().__init__(parent)
self.title("Create New Virtual Environment")
self.transient(parent)
self.grab_set()
self.result = None
self.package_manager = package_manager
self.current_interpreter_path = current_interpreter_path
main_frame = ttk.Frame(self, padding=15)
main_frame.pack(fill=tk.BOTH, expand=True)
path_frame = ttk.Frame(main_frame)
path_frame.pack(fill=tk.X, expand=True, pady=(0, 10))
ttk.Label(path_frame, text="Environment Folder:", width=18).pack(side=tk.LEFT)
self.path_var = tk.StringVar()
path_entry = ttk.Entry(path_frame, textvariable=self.path_var)
path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
browse_btn = ttk.Button(path_frame, text="Browse...", command=self._browse_path)
browse_btn.pack(side=tk.LEFT)
self.version_var = tk.StringVar()
if self.package_manager == 'uv':
version_frame = ttk.Frame(main_frame)
version_frame.pack(fill=tk.X, expand=True, pady=(0, 15))
label = ttk.Label(version_frame, text="Python Version:", width=18)
label.pack(side=tk.LEFT)
Tooltip(label, "Specify a Python version for `uv` to install (e.g., 3.11, 3.12.1).\nLeave blank to use the current base interpreter.")
version_entry = ttk.Entry(version_frame, textvariable=self.version_var)
version_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
packages_lf = ttk.LabelFrame(main_frame, text="Initial Packages (optional, one per line)", padding=10)
packages_lf.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
self.packages_text = scrolledtext.ScrolledText(packages_lf, height=6, wrap=tk.WORD, font=("Segoe UI", 9))
self.packages_text.pack(fill=tk.BOTH, expand=True)
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(fill=tk.X, pady=(5, 0))
ttk.Button(btn_frame, text="Create", command=self._on_create).pack(side=tk.RIGHT)
ttk.Button(btn_frame, text="Cancel", command=self.destroy).pack(side=tk.RIGHT, padx=(0, 5))
self.wait_window()
def _browse_path(self):
path = filedialog.askdirectory(title="Select Folder for New Environment")
if path:
self.path_var.set(path)
def _on_create(self):
path = self.path_var.get().strip()
if not path:
messagebox.showerror("Input Required", "Please specify a location for the environment.", parent=self)
return
packages_str = self.packages_text.get("1.0", tk.END).strip()
packages = [line.strip() for line in packages_str.splitlines() if line.strip()]
self.result = VenvConfig(
path=path,
python_version=self.version_var.get().strip(),
packages=packages
)
self.destroy()
class PyProjectInstallDialog(tk.Toplevel):
"""Dialog to select dependency groups from a pyproject.toml."""
def __init__(self, parent, dependencies):
super().__init__(parent)
self.title("Install from pyproject.toml")
self.transient(parent)
self.grab_set()
self.result = None
self.dependencies = dependencies
self.option_vars = {}
main_frame = ttk.Frame(self, padding=15)
main_frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(main_frame, text="Select dependency groups to install:", font=('Segoe UI', 10, 'bold')).pack(anchor='w', pady=(0, 10))
main_deps_lf = ttk.LabelFrame(main_frame, text=f"Main Dependencies ({len(self.dependencies['main'])})", padding=10)
main_deps_lf.pack(fill=tk.BOTH, expand=True, pady=5)
main_text = scrolledtext.ScrolledText(main_deps_lf, height=5, wrap=tk.WORD, font=("Segoe UI", 9))
main_text.pack(fill=tk.BOTH, expand=True)
main_text.insert(tk.END, "\n".join(self.dependencies['main']) or "None")
main_text.config(state=tk.DISABLED)
if self.dependencies['optional']:
opt_deps_lf = ttk.LabelFrame(main_frame, text="Optional Dependencies", padding=10)
opt_deps_lf.pack(fill=tk.BOTH, expand=True, pady=5)
for group_name in sorted(self.dependencies['optional'].keys()):
self.option_vars[group_name] = tk.BooleanVar()
group_size = len(self.dependencies['optional'][group_name])
cb = ttk.Checkbutton(opt_deps_lf, text=f"{group_name} ({group_size} packages)", variable=self.option_vars[group_name])
cb.pack(anchor='w')
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(fill=tk.X, pady=(10, 0))
ttk.Button(btn_frame, text="Install", command=self._on_install).pack(side=tk.RIGHT)
ttk.Button(btn_frame, text="Cancel", command=self.destroy).pack(side=tk.RIGHT, padx=(0, 5))
self.wait_window()
def _on_install(self):
packages_to_install = list(self.dependencies['main'])
for group_name, var in self.option_vars.items():
if var.get():
packages_to_install.extend(self.dependencies['optional'][group_name])
self.result = list(set(packages_to_install)) # Use set to remove duplicates
self.destroy()
# === Logic Helpers ===
class SettingsManager:
"""Handles loading and saving application settings."""
def __init__(self, file_path):
self.file_path = file_path
self.defaults = {
'auto_check_updates': True,
'cache_expiry_hours': 24,
'interpreters': [sys.executable]
}
def load(self):
"""Loads settings from JSON, applying defaults for missing keys."""
if os.path.exists(self.file_path):
try:
with open(self.file_path, 'r') as f:
settings = json.load(f)
for key, value in self.defaults.items():
settings.setdefault(key, value)
except (json.JSONDecodeError, TypeError):
settings = self.defaults
else:
settings = self.defaults
if sys.executable not in settings['interpreters']:
settings['interpreters'].insert(0, sys.executable)
seen = set()
unique_interpreters = [x for x in settings['interpreters'] if not (x in seen or seen.add(x))]
unique_interpreters.sort(key=lambda x: x == sys.executable, reverse=True)
settings['interpreters'] = unique_interpreters
return settings
def save(self, settings):
"""Saves the provided settings dictionary to the JSON file."""
with open(self.file_path, 'w') as f:
json.dump(settings, f, indent=2)
class CacheManager:
"""Handles reading from and writing to the package cache files."""
def __init__(self, template_path):
self.template_path = template_path
def _get_path(self, interpreter_path):
"""Generates a unique cache file path for the current interpreter."""
env_hash = hashlib.sha1(interpreter_path.encode()).hexdigest()[:10]
return self.template_path.format(env_hash=env_hash)
def load(self, interpreter_path, expiry_hours):
"""Loads packages from the cache if it exists and is not expired."""
cache_path = self._get_path(interpreter_path)
if not os.path.exists(cache_path): return None
try:
with open(cache_path, 'r', encoding='utf-8') as f:
cache_data = json.load(f)
if cache_data.get("version") != CACHE_VERSION: return None
if expiry_hours > 0:
cache_time = datetime.datetime.fromisoformat(cache_data.get("timestamp"))
if datetime.datetime.now() - cache_time > datetime.timedelta(hours=expiry_hours):
return None
return cache_data
except Exception as e:
print(f"Error loading or validating cache: {e}")
return None
def save(self, interpreter_path, data):
"""Saves data to a JSON cache file."""
cache_path = self._get_path(interpreter_path)
try:
data_to_save = {
"version": CACHE_VERSION,
"timestamp": datetime.datetime.now().isoformat(),
**data
}
with open(cache_path, 'w', encoding='utf-8') as f:
json.dump(data_to_save, f)
except Exception as e:
print(f"Error saving cache: {e}")
def clear_all(self):
"""Deletes ALL package cache files across all known environments."""
cache_dir = os.path.dirname(self.template_path)
base_name = os.path.basename(self.template_path).split('{')[0]
cleared_count = 0
if not os.path.isdir(cache_dir):
return 0, "No cache directory found."
for filename in os.listdir(cache_dir):
if filename.startswith(base_name) and filename.endswith(".json"):
try:
os.remove(os.path.join(cache_dir, filename))
cleared_count += 1
except OSError as e:
return cleared_count, f"Failed to clear cache file {filename}: {e}"
return cleared_count, None
class StatusManager:
"""Manages updates to the action status bar to reduce code repetition."""
def __init__(self, root, action_status_var):
self.root = root
self.action_status_var = action_status_var
def update(self, message, clear_after_ms=3000):
"""Sets a status message that clears automatically."""
self.action_status_var.set(message)
if clear_after_ms:
self.root.after(clear_after_ms, lambda: self._clear_if_matches(message))
def set_persistent(self, message):
"""Sets a status message that does not clear automatically."""
self.action_status_var.set(message)
def _clear_if_matches(self, message):
"""Clears the status bar only if the message hasn't changed."""
if self.action_status_var.get() == message:
self.action_status_var.set("")
# === Main Application Class ===
class PackageManagerApp:
def __init__(self, root):
self.root = root
self.root.title(f"Python Package Manager 2.5+")
self.root.geometry("950x650")
self.style = ttk.Style()
self.style.theme_use('clam')
self.style.configure("Outdated.TButton", foreground="darkorange", font=('Segoe UI', 9, 'bold'))
self.style.configure("Action.TLabel", foreground="gray")
self.style.configure("UV.TLabel", foreground="#4B0082", font=('Segoe UI', 9, 'bold'))
self.all_packages = []
self.outdated_packages = {}
self.reverse_deps = defaultdict(list)
self.orphaned_packages_cache = []
self.damaged_packages_cache = []
self.vulnerabilities_cache = {}
self.current_interpreter = sys.executable
self.task_queue = queue.Queue()
self.current_scan_id = 0
self.last_sort_column = 'Name'
self.last_sort_reverse = False
self.force_reinstall_var = tk.BooleanVar()
self.package_manager = 'pip'
self.package_manager_path = None
self.process_lock = threading.Lock()
self.active_process = None
self.RESTART_REQUIRED_PACKAGES = {'tkinterdnd2', 'packaging'}
self.check_deps_var = tk.BooleanVar(value=True)
self.check_hashes_var = tk.BooleanVar(value=False)
self.check_import_var = tk.BooleanVar(value=False)
self.check_metadata_files_var = tk.BooleanVar(value=False)
self.settings_manager = SettingsManager(SETTINGS_FILE)
self.cache_manager = CacheManager(CACHE_FILE_TEMPLATE)
self.settings = self.settings_manager.load()
self._create_widgets()
self.status_manager = StatusManager(self.root, self.action_status_var)
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.root.after(100, self._process_queue)
self.status_manager.set_persistent("Initializing...")
self.root.after(150, self.initial_load)
self.root.after(200, self._validate_interpreters_on_startup)
self.root.after(250, self._detect_package_manager)
self.root.after(300, lambda: self._show_tool('vulnerabilities'))
def on_closing(self):
"""Handles the window closing event to shut down background processes."""
self.status_manager.set_persistent("Shutting down...")
self._terminate_active_process()
self.root.destroy()
def _detect_package_manager(self):
"""Checks for `uv` and sets the package manager preference."""
uv_path = shutil.which("uv")
try:
if uv_path:
subprocess.run([uv_path, "--version"], check=True, capture_output=True, creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0)
self.package_manager = 'uv'
self.package_manager_path = uv_path
self.manager_indicator_label.config(text="UV ⚡ (Faster)", style="UV.TLabel")
Tooltip(self.manager_indicator_label, f"Using 'uv' package manager found at:\n{uv_path}")
self.create_venv_btn.config(state=tk.NORMAL)
return
except (subprocess.CalledProcessError, FileNotFoundError):
pass
self.package_manager = 'pip'
self.package_manager_path = None
self.manager_indicator_label.config(text="pip (Default)", style="TLabel")
Tooltip(self.manager_indicator_label, "Using the standard 'pip' module for the selected environment.")
self.create_venv_btn.config(state=tk.NORMAL)
def _terminate_active_process(self):
"""Terminates the currently running subprocess, if any. Thread-safe."""
proc_to_kill = None
with self.process_lock:
if self.active_process:
proc_to_kill = self.active_process
if proc_to_kill and proc_to_kill.poll() is None:
try:
print(f"Terminating active process {proc_to_kill.pid}...")
proc_to_kill.terminate()
proc_to_kill.wait(timeout=1)
print("Active process terminated.")
except Exception as e:
print(f"Error terminating active process: {e}")
def _save_settings(self, *args):
"""Saves current settings to the JSON file."""
self.settings['auto_check_updates'] = self.auto_check_var.get()
try:
self.settings['cache_expiry_hours'] = int(self.cache_expiry_var.get())
except (ValueError, tk.TclError):
self.settings['cache_expiry_hours'] = 24
if hasattr(self, 'interpreter_combo'):
self.settings['interpreters'] = list(self.interpreter_combo['values'])
self.settings_manager.save(self.settings)
self.status_manager.update("Settings saved.")
def initial_load(self):
"""Performs the initial package load, using cache if available and valid."""
run_update_check = self.settings.get('auto_check_updates', True)
cache_data = self.cache_manager.load(self.current_interpreter, self.settings.get('cache_expiry_hours', 24))
if cache_data:
self.all_packages = cache_data.get("packages", [])
self.reverse_deps = defaultdict(list, cache_data.get("reverse_deps", {}))
self.damaged_packages_cache = cache_data.get("damaged_packages", [])
self._populate_tree()
self._filter_packages()
self._start_full_refresh_chain(run_update_check=run_update_check)
else:
self._start_full_refresh_chain(run_update_check=run_update_check)
self.notebook.select(self.manage_frame)
def refresh_installed_only(self):
"""Refreshes only the list of installed packages without checking for updates."""
self._start_full_refresh_chain(run_update_check=False)
def refresh_and_check_updates(self):
"""Performs a full refresh of installed packages and checks for updates."""
self._start_full_refresh_chain(run_update_check=True)
def check_for_updates_only(self):
"""Checks for outdated packages without rescanning the installed list."""
if not self.all_packages:
messagebox.showinfo("Info", "Load a package list first with a refresh.")
return
self._update_ui_state(True)
scan_id = self.current_scan_id + 1
self.current_scan_id = scan_id
self._queue_status_update("Checking for outdated packages...", scan_id)
self._run_in_thread(self._check_for_outdated_packages_task, scan_id, on_complete=lambda res: self._on_outdated_checked(res, scan_id))
def _start_full_refresh_chain(self, run_update_check=True):
"""Initiates the package loading process in a background thread."""
self._terminate_active_process()
self._update_ui_state(True)
scan_id = self.current_scan_id + 1
self.current_scan_id = scan_id
on_complete_callback = (lambda res: self._on_packages_loaded_then_check(res, scan_id)) if run_update_check else (lambda res: self._on_installed_loaded(res, scan_id))
self._run_in_thread(self._load_packages_task, scan_id, on_complete=on_complete_callback)
def _create_widgets(self):
"""Creates and arranges all GUI widgets."""
main_frame = ttk.Frame(self.root, padding="10")
main_frame.pack(fill=tk.BOTH, expand=True)
self.notebook = ttk.Notebook(main_frame)
self.notebook.pack(fill=tk.BOTH, expand=True, pady=(0, 5))
self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)
self.manage_frame = ttk.Frame(self.notebook, padding="5")
self.notebook.add(self.manage_frame, text="Manage Packages")
self._create_manage_tab()
self.install_frame = ttk.Frame(self.notebook, padding="20")
self.notebook.add(self.install_frame, text="Install Packages")
self._create_install_tab(self.install_frame)
self.tools_tab_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(self.tools_tab_frame, text="Tools")
self._create_tools_tab(self.tools_tab_frame)
settings_frame = ttk.Frame(self.notebook, padding="20")
self.notebook.add(settings_frame, text="Settings")
self._create_settings_tab(settings_frame)
status_frame = tk.Frame(main_frame, relief=tk.SUNKEN, bd=1)
status_frame.pack(side=tk.BOTTOM, fill=tk.X)
self.status_var = tk.StringVar(value="Welcome!")
self.action_status_var = tk.StringVar(value="Initializing...")
ttk.Label(status_frame, textvariable=self.status_var, anchor=tk.W, padding=(5, 2, 5, 0)).pack(fill=tk.X)
ttk.Label(status_frame, textvariable=self.action_status_var, anchor=tk.W, padding=(5, 0, 5, 2), style="Action.TLabel").pack(fill=tk.X)
def _create_manage_tab(self):
"""Creates the widgets for the 'Manage Packages' tab."""
controls_frame = ttk.Frame(self.manage_frame)
controls_frame.pack(fill=tk.X, pady=5)
self.refresh_menubtn = ttk.Menubutton(controls_frame, text="🔄 Refresh", style="TButton")
self.refresh_menubtn.pack(side=tk.LEFT, padx=(0, 10))
refresh_menu = tk.Menu(self.refresh_menubtn, tearoff=0)
refresh_menu.add_command(label="Refresh Installed List", command=self.refresh_installed_only)
refresh_menu.add_command(label="Check For Updates Only", command=self.check_for_updates_only)
refresh_menu.add_separator()
refresh_menu.add_command(label="Full Refresh & Update Check", command=self.refresh_and_check_updates)
self.refresh_menubtn['menu'] = refresh_menu
self.upgrade_all_btn = ttk.Button(controls_frame, text="Upgrade All Outdated", command=self.upgrade_all_outdated, state=tk.DISABLED)
self.upgrade_all_btn.pack(side=tk.LEFT, padx=(0, 10))
self.show_outdated_var = tk.BooleanVar()
ttk.Checkbutton(controls_frame, text="Show only outdated", variable=self.show_outdated_var, command=self._filter_packages).pack(side=tk.LEFT, padx=(5, 5))
ttk.Label(controls_frame, text="Search:").pack(side=tk.LEFT, padx=(10, 5))
self.search_var = tk.StringVar()
self.search_var.trace_add("write", self._filter_packages)
self.search_entry = ttk.Entry(controls_frame, textvariable=self.search_var, width=30)
self.search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
tree_frame = ttk.Frame(self.manage_frame)
tree_frame.pack(fill=tk.BOTH, expand=True, pady=5)
columns = ("Name", "Version", "Size", "Date")
self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings", selectmode="extended")
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
for col in columns:
self.tree.heading(col, text=col.replace("_", " "), command=lambda c=col: self._sort_column(c, False))
self.tree.column("Name", width=250)
self.tree.column("Version", width=150, anchor=tk.CENTER)
self.tree.column("Size", width=100, anchor=tk.E)
self.tree.column("Date", width=120, anchor=tk.CENTER)
self.tree.tag_configure('outdated', background='#FFFACD')
self.tree.tag_configure('vulnerable', foreground='red')
scrollbar = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.configure(yscrollcommand=scrollbar.set)
self.tree.bind('<<TreeviewSelect>>', lambda e: self._update_status_bar())
self.tree.bind("<Button-3>", self._show_context_menu)
self._create_context_menu()
def _create_install_tab(self, parent_frame):
"""Creates the widgets for the 'Install Packages' tab."""
# --- Install from PyPI ---
pypi_lf = ttk.LabelFrame(parent_frame, text="Install from PyPI", padding=10)
pypi_lf.pack(fill=tk.X, expand=False, pady=(0, 10), anchor='n')
ttk.Label(pypi_lf, text="Package name (e.g., 'requests' or 'requests==2.25.1'):").pack(anchor='w')
install_entry_frame = ttk.Frame(pypi_lf)
install_entry_frame.pack(fill=tk.X, pady=5)
self.package_entry = ttk.Entry(install_entry_frame, width=50)
self.package_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, ipady=4)
install_btn_frame = ttk.Frame(pypi_lf)
install_btn_frame.pack(fill=tk.X)
self.force_reinstall_check = ttk.Checkbutton(install_btn_frame, text="Force Reinstall", variable=self.force_reinstall_var)
self.force_reinstall_check.pack(side=tk.LEFT, anchor='w')
Tooltip(self.force_reinstall_check, "Forces a complete reinstall by ignoring caches and existing files.\nAdds --force-reinstall --no-cache-dir (pip)\nor --reinstall --no-cache (uv).")
self.install_btn = ttk.Button(install_btn_frame, text="Install Package", command=self.install_package)
self.install_btn.pack(side=tk.RIGHT, anchor='e')
find_versions_btn = ttk.Button(install_btn_frame, text="Find Versions...", command=self.show_version_selector)
find_versions_btn.pack(side=tk.RIGHT, anchor='e', padx=(0, 5))
# --- Install from File (container) ---
from_file_lf = ttk.LabelFrame(parent_frame, text="Install from File", padding=10)
from_file_lf.pack(fill=tk.X, expand=False, pady=(0, 10), anchor='n')
if DND_AVAILABLE:
from_file_lf.drop_target_register(DND_FILES)
from_file_lf.dnd_bind('<<Drop>>', self.handle_file_drop)
hint_label = ttk.Label(from_file_lf, text="(Or drop a requirements.txt / pyproject.toml file here)", style="Action.TLabel")
hint_label.pack(pady=(5, 0))
# --- Sub-frames for each file type ---
req_frame = ttk.Frame(from_file_lf)
req_frame.pack(fill=tk.X, pady=2)
ttk.Button(req_frame, text="Install from requirements.txt...", command=self.install_from_file).pack()
toml_frame = ttk.Frame(from_file_lf)
toml_frame.pack(fill=tk.X, pady=2)
ttk.Button(toml_frame, text="Install from pyproject.toml...", command=self.install_from_pyproject).pack()
# --- Optional Components ---
if not all([DND_AVAILABLE, PACKAGING_AVAILABLE, TOMLI_AVAILABLE]):
components_lf = ttk.LabelFrame(parent_frame, text="Additional Components", padding=10)
components_lf.pack(fill=tk.X, expand=False, anchor='n')
if not PACKAGING_AVAILABLE:
pkg_frame = ttk.Frame(components_lf)
pkg_frame.pack(fill=tk.X, pady=2)
pkg_btn = ttk.Button(pkg_frame, text="Install 'packaging'", command=lambda: self._install_optional_dependency(package_name='packaging', frame_widget=pkg_frame))
pkg_btn.pack(side=tk.LEFT)
Tooltip(pkg_btn, "Provides accurate version sorting in the package list.\nA restart is required after installation.")
ttk.Label(pkg_frame, text="- for accurate version sorting").pack(side=tk.LEFT, padx=5)
if not DND_AVAILABLE:
dnd_frame = ttk.Frame(components_lf)
dnd_frame.pack(fill=tk.X, pady=2)
dnd_btn = ttk.Button(dnd_frame, text="Install 'tkinterdnd2'", command=lambda: self._install_optional_dependency(package_name='tkinterdnd2', frame_widget=dnd_frame))
dnd_btn.pack(side=tk.LEFT)
Tooltip(dnd_btn, "Enables drag-and-drop support for requirements files.\nA restart is required after installation.")
ttk.Label(dnd_frame, text="- for drag-and-drop support").pack(side=tk.LEFT, padx=5)
if not TOMLI_AVAILABLE:
toml_frame_install = ttk.Frame(components_lf)
toml_frame_install.pack(fill=tk.X, pady=2)
toml_btn = ttk.Button(toml_frame_install, text="Install 'tomli'", command=lambda: self._install_optional_dependency(package_name='tomli', frame_widget=toml_frame_install))
toml_btn.pack(side=tk.LEFT)
Tooltip(toml_btn, "Enables reading dependencies from pyproject.toml files.")
ttk.Label(toml_frame_install, text="- to read pyproject.toml files").pack(side=tk.LEFT, padx=5)
def _install_optional_dependency(self, package_name, target_interpreter=None, frame_widget=None, on_success=None):
"""Installs an optional dependency into a specified environment."""
target_env = target_interpreter or sys.executable
env_name = "the selected environment" if target_interpreter else "the application's own environment"
msg = (f"This feature requires the '{package_name}' library. "
f"It will be installed into {env_name}.\n\n"
"Do you want to proceed?")
if messagebox.askyesno(f"Install Optional Component", msg):
if frame_widget:
for widget in frame_widget.winfo_children():
widget.config(state=tk.DISABLED)
def on_complete():
self.status_manager.update(f"'{package_name}' installed successfully.")
if on_success:
# A small trick to make the import available in the current run
if package_name == 'tomli':
global TOMLI_AVAILABLE, tomli
try:
import tomli
TOMLI_AVAILABLE = True
except ImportError:
pass
on_success()
elif not target_interpreter:
messagebox.showinfo("Installation Successful",
f"'{package_name}' has been installed.\n\nPlease restart the application to use the new functionality.")
if self.package_manager == 'uv' and self.package_manager_path:
command = [self.package_manager_path, "pip", "install", package_name, "-p", target_env]
else:
command = [target_env, "-m", "pip", "install", package_name]
self._run_pip_command(command, f"Installing {package_name}", on_complete)
def _create_tools_tab(self, parent_frame):
"""Creates the widgets for the Tools tab with a switcher."""
controls_frame = ttk.Frame(parent_frame)
controls_frame.pack(side=tk.TOP, fill=tk.X, pady=(0, 10))
ttk.Button(controls_frame, text="Vulnerability Scan", command=lambda: self._show_tool('vulnerabilities')).pack(side=tk.LEFT, padx=2)
ttk.Button(controls_frame, text="Damaged Packages", command=lambda: self._show_tool('damaged')).pack(side=tk.LEFT, padx=2)
ttk.Button(controls_frame, text="Orphaned Packages", command=lambda: self._show_tool('orphans')).pack(side=tk.LEFT, padx=2)
ttk.Button(controls_frame, text="Compiler", command=lambda: self._show_tool('compiler')).pack(side=tk.LEFT, padx=2)
self.tools_content_frame = ttk.Frame(parent_frame)
self.tools_content_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
self.vulnerabilities_frame = self._create_vulnerability_tool()
self.damaged_frame = self._create_damaged_packages_tool()
self.orphans_frame = self._create_orphans_tool()
self.compiler_frame = self._create_compiler_tool()
self.tool_frames = {
'vulnerabilities': self.vulnerabilities_frame,
'damaged': self.damaged_frame,
'orphans': self.orphans_frame,
'compiler': self.compiler_frame,
}
def _show_tool(self, tool_name):
"""Hides all tool frames and shows the selected one."""
for frame in self.tool_frames.values():
frame.pack_forget()
frame_to_show = self.tool_frames.get(tool_name)
if frame_to_show:
frame_to_show.pack(fill=tk.BOTH, expand=True)
def _create_generic_treeview(self, parent, columns_config, selectmode='extended'):
"""
Creates a generic Treeview with a scrollbar inside a frame.
:param parent: The parent widget for the treeview frame.
:param columns_config: A dictionary mapping column names to their properties (e.g., width, anchor).
:param selectmode: The selection mode for the treeview ('extended', 'browse', etc.).
:return: The created ttk.Treeview widget.
"""
tree_frame = ttk.Frame(parent)
tree_frame.pack(fill=tk.BOTH, expand=True, pady=5)
columns = tuple(columns_config.keys())
tree = ttk.Treeview(tree_frame, columns=columns, show="headings", selectmode=selectmode)
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
for col_name, col_props in columns_config.items():
tree.heading(col_name, text=col_name)
if col_props:
tree.column(col_name, **col_props)
scrollbar = ttk.Scrollbar(tree_frame, orient="vertical", command=tree.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
tree.configure(yscrollcommand=scrollbar.set)
return tree
def _create_vulnerability_tool(self):
"""Creates the UI for the vulnerability scanner."""
vuln_lf = ttk.LabelFrame(self.tools_content_frame, text="Vulnerability Scanner (via pip-audit)", padding=10)
controls = ttk.Frame(vuln_lf)
controls.pack(fill=tk.X, pady=5)
self.run_vuln_scan_btn = ttk.Button(controls, text="Run Vulnerability Scan", command=self.run_vulnerability_scan)
self.run_vuln_scan_btn.pack(side=tk.LEFT)
self.vuln_status_label = ttk.Label(controls, text="Check the selected environment for known vulnerabilities.")
self.vuln_status_label.pack(side=tk.LEFT, padx=10)
columns_config = {
"Package": {"width": 120},
"Version": {"width": 80},
"ID": {"width": 120},
"Description": {"width": 300},
"Fixed In": {"width": 100}
}
self.vuln_tree = self._create_generic_treeview(vuln_lf, columns_config, selectmode='browse')
return vuln_lf
def _create_damaged_packages_tool(self):
"""Creates the UI for the damaged package finder tool."""
damaged_lf = ttk.LabelFrame(self.tools_content_frame, text="Analysis of Damaged Packages", padding=10)
controls = ttk.Frame(damaged_lf)
controls.pack(fill=tk.X, pady=5)
self.find_damaged_btn = ttk.Button(controls, text="Find Damaged Packages", command=self.find_damaged_packages)
self.find_damaged_btn.pack(side=tk.LEFT)
self.reinstall_damaged_btn = ttk.Button(controls, text="Reinstall Selected", command=self.reinstall_selected_damaged, state=tk.DISABLED)
self.reinstall_damaged_btn.pack(side=tk.LEFT, padx=10)
Tooltip(self.reinstall_damaged_btn, "Attempt a force-reinstall of the selected package(s).\nThis can fix dependency issues, corrupted files, and failed imports.")
self.damaged_status_label = ttk.Label(controls, text="Select checks and click 'Find' to scan the environment.")
self.damaged_status_label.pack(side=tk.LEFT, padx=5)
checks_frame = ttk.Frame(damaged_lf, padding=(0, 5, 0, 10))
checks_frame.pack(fill=tk.X)
c1 = ttk.Checkbutton(checks_frame, text="Dependency conflicts (pip check)", variable=self.check_deps_var)
c1.grid(row=0, column=0, sticky='w', padx=5)
Tooltip(c1, "Runs 'pip check' to find packages with incompatible or missing dependencies.")
c2 = ttk.Checkbutton(checks_frame, text="File integrity (hashes)", variable=self.check_hashes_var)
c2.grid(row=0, column=1, sticky='w', padx=5)
Tooltip(c2, "Verifies SHA256 hashes of installed files against the package's RECORD file.\n(Can be slow)")
c3 = ttk.Checkbutton(checks_frame, text="Test import", variable=self.check_import_var)
c3.grid(row=1, column=0, sticky='w', padx=5)
Tooltip(c3, "Attempts to import each package in a subprocess to catch basic runtime errors.\n(Can be slow)")
c4 = ttk.Checkbutton(checks_frame, text="Missing metadata files", variable=self.check_metadata_files_var)
c4.grid(row=1, column=1, sticky='w', padx=5)
Tooltip(c4, "Checks if all files listed in the package metadata actually exist on disk.")
columns_config = {
"Package": {"width": 150},
"Problem": {"width": 180},
"Details": {"width": 350}
}
self.damaged_tree = self._create_generic_treeview(damaged_lf, columns_config, selectmode='extended')
self.damaged_tree.bind("<<TreeviewSelect>>", self._on_damaged_selection_changed)
return damaged_lf
def _create_orphans_tool(self):
"""Creates the UI for the orphaned package finder tool."""
orphan_lf = ttk.LabelFrame(self.tools_content_frame, text="Orphaned Packages Analysis", padding=10)
orphan_controls_frame = ttk.Frame(orphan_lf)
orphan_controls_frame.pack(fill=tk.X, pady=5)
self.find_orphans_btn = ttk.Button(orphan_controls_frame, text="Find Orphaned Packages", command=self.find_orphaned_packages)
self.find_orphans_btn.pack(side=tk.LEFT)
self.uninstall_orphans_btn = ttk.Button(orphan_controls_frame, text="Uninstall Selected", command=self.uninstall_selected_orphans, state=tk.DISABLED)
self.uninstall_orphans_btn.pack(side=tk.LEFT, padx=10)
self.orphan_status_label = ttk.Label(orphan_controls_frame, text="Click 'Find' to scan for orphaned packages.")
self.orphan_status_label.pack(side=tk.LEFT, padx=5)
columns_config = {
"Name": {"width": 250},
"Version": {"width": 150, "anchor": tk.CENTER},
"Size": {"width": 100, "anchor": tk.E},
"Date": {"width": 120, "anchor": tk.CENTER}
}
self.orphan_tree = self._create_generic_treeview(orphan_lf, columns_config, selectmode='extended')
self.orphan_tree.bind('<<TreeviewSelect>>', self._on_orphan_selection_changed)
return orphan_lf
def _create_compiler_tool(self):
"""Creates the UI for the requirements compiler tool."""
compile_lf = ttk.LabelFrame(self.tools_content_frame, text="Compile requirements.in (via pip-tools)", padding=10)
if DND_AVAILABLE:
compile_lf.drop_target_register(DND_FILES)
compile_lf.dnd_bind('<<Drop>>', self._handle_req_in_drop)
in_frame = ttk.Frame(compile_lf)
in_frame.pack(fill=tk.X, expand=True, pady=2)
ttk.Label(in_frame, text="Input (.in):", width=12).pack(side=tk.LEFT)
self.req_in_path = tk.StringVar()
in_entry = ttk.Entry(in_frame, textvariable=self.req_in_path)
in_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 5))
in_btn = ttk.Button(in_frame, text="Browse...", command=self._browse_for_req_in_file)
in_btn.pack(side=tk.LEFT)
out_frame = ttk.Frame(compile_lf)
out_frame.pack(fill=tk.X, expand=True, pady=2)
ttk.Label(out_frame, text="Output (.txt):", width=12).pack(side=tk.LEFT)
self.req_out_path = tk.StringVar()
out_entry = ttk.Entry(out_frame, textvariable=self.req_out_path)
out_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 5))
out_btn = ttk.Button(out_frame, text="Browse...", command=self._browse_for_req_out_file)
out_btn.pack(side=tk.LEFT)
compile_btn_frame = ttk.Frame(compile_lf)
compile_btn_frame.pack(fill=tk.X, pady=(10, 0))
self.compile_reqs_btn = ttk.Button(compile_lf, text="Compile", command=self.compile_requirements)
self.compile_reqs_btn.pack(side=tk.RIGHT)
return compile_lf
def _create_settings_tab(self, parent_frame):
"""Creates the widgets for the 'Settings' tab."""
env_frame = ttk.LabelFrame(parent_frame, text="Python Environment Management", padding=10)
env_frame.pack(fill=tk.X, pady=5)
combo_frame = ttk.Frame(env_frame)
combo_frame.pack(fill=tk.X, pady=(0, 5))
self.interpreter_var = tk.StringVar(value=self.current_interpreter)
self.interpreter_combo = ttk.Combobox(combo_frame, textvariable=self.interpreter_var, values=self.settings.get('interpreters', []), state='readonly')
self.interpreter_combo.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
self.interpreter_combo.bind('<<ComboboxSelected>>', self._on_interpreter_selected)
browse_btn = ttk.Button(combo_frame, text="...", command=self._browse_for_interpreter, width=4)
browse_btn.pack(side=tk.LEFT)
Tooltip(browse_btn, "Add an existing Python interpreter (e.g., from a venv)")
env_actions_frame = ttk.Frame(env_frame)
env_actions_frame.pack(fill=tk.X, pady=(5, 0))
self.remove_interpreter_btn = ttk.Button(env_actions_frame, text="Remove Selected", command=self._remove_interpreter)
self.remove_interpreter_btn.pack(side=tk.RIGHT, padx=(5, 0))
Tooltip(self.remove_interpreter_btn, "Remove the selected interpreter from the list.\nThe currently active interpreter cannot be removed.")
self.create_venv_btn = ttk.Button(env_actions_frame, text="Create venv", command=self._create_venv, state=tk.DISABLED)
self.create_venv_btn.pack(side=tk.RIGHT)
Tooltip(self.create_venv_btn, "Create a new virtual environment.\n(Advanced options available if 'uv' is detected)")
startup_lf = ttk.LabelFrame(parent_frame, text="Startup & Refresh", padding=10)
startup_lf.pack(fill=tk.X, pady=5)
self.auto_check_var = tk.BooleanVar(value=self.settings.get('auto_check_updates', True))
auto_check_btn = ttk.Checkbutton(startup_lf, text="Automatically check for outdated packages on startup", variable=self.auto_check_var)
auto_check_btn.pack(anchor='w')
self.auto_check_var.trace_add("write", self._save_settings)
Tooltip(auto_check_btn, "If enabled, the app will check for updates online automatically on startup.\nDisabling this leads to a faster, offline startup.")
cache_lf = ttk.LabelFrame(parent_frame, text="Cache Management", padding=10)
cache_lf.pack(fill=tk.X, pady=10)
expiry_frame = ttk.Frame(cache_lf)
expiry_frame.pack(fill=tk.X)
self.cache_expiry_var = tk.StringVar(value=str(self.settings.get('cache_expiry_hours', 24)))
cache_expiry_label = ttk.Label(expiry_frame, text="Cache expiry (hours):")
cache_expiry_label.pack(side=tk.LEFT)
cache_expiry_entry = ttk.Entry(expiry_frame, textvariable=self.cache_expiry_var, width=5)
cache_expiry_entry.pack(side=tk.LEFT, padx=5)
cache_expiry_entry.bind("<FocusOut>", self._save_settings)
Tooltip(cache_expiry_label, "How long package data is cached before a full refresh is required on startup.\nSet to 0 to always refresh on startup.")
clear_cache_btn = ttk.Button(cache_lf, text="Clear All Package Caches Now", command=self._clear_cache)
clear_cache_btn.pack(pady=(10, 0))
Tooltip(clear_cache_btn, "Deletes all cached package lists for all environments.\nThe next startup for each will perform a full, fresh scan.")
about_lf = ttk.LabelFrame(parent_frame, text="About", padding=10)
about_lf.pack(fill=tk.X, pady=10)
ttk.Label(about_lf, text=f"Version: {APP_VERSION}").pack(anchor='w')
ttk.Label(about_lf, text=f"Build: {BUILD_NUMBER}").pack(anchor='w')
ttk.Label(about_lf, text="Author: Olexandr_43").pack(anchor='w')