-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlablink.py
More file actions
executable file
·1980 lines (1686 loc) · 73.9 KB
/
lablink.py
File metadata and controls
executable file
·1980 lines (1686 loc) · 73.9 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
"""
LabLink - Unified GUI Entry Point
==================================
A comprehensive GUI launcher for LabLink that provides:
- Environment compatibility checking
- Dependency verification and installation
- LED status indicators for system health
- One-click server/client launching
- Issue resolution and troubleshooting
Author: LabLink Team
License: MIT
"""
import sys
import os
import subprocess
import platform
import json
import shutil
import logging
import time
from pathlib import Path
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass
from enum import Enum
# Read version from VERSION file (single source of truth)
_version_file = Path(__file__).parent / "VERSION"
__version__ = _version_file.read_text().strip() if _version_file.exists() else "1.2.0"
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s',
handlers=[
logging.FileHandler('lablink_debug.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Log startup
logger.info("=" * 70)
logger.info("LabLink Launcher Debug Log Started")
logger.info("=" * 70)
# Bootstrap check: Ensure pip is available before trying to install PyQt6
def check_and_install_pip():
"""Check if pip is available, and install if needed."""
# Check if pip is available
result = subprocess.run(
[sys.executable, '-m', 'pip', '--version'],
capture_output=True,
text=True,
check=False
)
if result.returncode != 0:
print("\n" + "="*70)
print("ERROR: pip is not installed")
print("="*70)
print("\nLabLink requires pip to install dependencies.")
print("\nOn Ubuntu 24.04, install pip with:")
print(" sudo apt update")
print(" sudo apt install -y python3-pip python3-venv")
print("\nOr use the system package manager to install LabLink dependencies.")
print("="*70 + "\n")
sys.exit(1)
def get_venv_paths(venv_name: str = "venv") -> Dict[str, Path]:
"""Get platform-appropriate virtual environment paths.
On Windows, venv uses 'Scripts' directory with .exe extensions.
On Linux/macOS, venv uses 'bin' directory without extensions.
Args:
venv_name: Name of the virtual environment directory
Returns:
Dictionary with 'base', 'bin', 'python', and 'pip' paths
"""
venv_base = Path(venv_name)
if sys.platform == "win32":
# Windows uses Scripts directory
venv_bin = venv_base / "Scripts"
venv_python = venv_bin / "python.exe"
venv_pip = venv_bin / "pip.exe"
else:
# Unix-like systems (Linux, macOS) use bin directory
venv_bin = venv_base / "bin"
venv_python = venv_bin / "python"
venv_pip = venv_bin / "pip"
return {
'base': venv_base,
'bin': venv_bin,
'python': venv_python,
'pip': venv_pip
}
# Qt imports with bootstrap handling
try:
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QGroupBox, QTextEdit, QDialog, QMessageBox,
QProgressBar, QScrollArea, QFrame, QComboBox
)
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal, QSize
from PyQt6.QtGui import QPainter, QColor, QFont, QPalette, QIcon
except ImportError:
print("\n" + "="*70)
print("PyQt6 is not installed - Setting up environment...")
print("="*70)
# Make sure pip is available first
check_and_install_pip()
# Check if Python is externally managed (PEP 668)
venv_paths = get_venv_paths()
venv_path = venv_paths['base']
needs_venv = False
# Check for EXTERNALLY-MANAGED marker
import sysconfig
stdlib = sysconfig.get_path('stdlib')
if stdlib:
marker = Path(stdlib) / 'EXTERNALLY-MANAGED'
if marker.exists():
needs_venv = True
print("\n⚠️ Detected externally-managed Python (Ubuntu 24.04/PEP 668)")
print("Creating virtual environment for LabLink...")
if needs_venv:
# Create venv if it doesn't exist
if not venv_path.exists():
try:
print(f"\nCreating virtual environment at {venv_path}...")
subprocess.check_call([sys.executable, "-m", "venv", "venv"])
print("✓ Virtual environment created")
except subprocess.CalledProcessError as e:
print("\n" + "="*70)
print("ERROR: Failed to create virtual environment")
print("="*70)
print(f"\nError: {e}")
print("\nPlease install python3-venv:")
print(" sudo apt update")
print(" sudo apt install -y python3-venv")
print("="*70 + "\n")
sys.exit(1)
# Install PyQt6 in venv
venv_python = venv_paths['python']
venv_pip = venv_paths['pip']
try:
print("\nInstalling PyQt6 in virtual environment...")
subprocess.check_call([str(venv_pip), "install", "PyQt6"])
print("\n" + "="*70)
print("✓ SUCCESS: Environment setup complete!")
print("="*70)
print("\nRestarting launcher with virtual environment...")
print("="*70 + "\n")
# Re-run this script with venv python
import os
os.execv(str(venv_python), [str(venv_python)] + sys.argv)
except subprocess.CalledProcessError as e:
print("\n" + "="*70)
print("ERROR: Failed to install PyQt6")
print("="*70)
print(f"\nError: {e}")
print("\nPlease try manually:")
print(" python3 -m venv venv")
if sys.platform == "win32":
print(" venv\\Scripts\\activate")
else:
print(" source venv/bin/activate")
print(" pip install PyQt6")
print(f" python3 {sys.argv[0]}")
print("="*70 + "\n")
sys.exit(1)
else:
# Try direct install (non-externally-managed system)
try:
print("\nInstalling PyQt6...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "PyQt6"])
print("\n" + "="*70)
print("SUCCESS: PyQt6 installed successfully!")
print("="*70)
print("\nPlease run the launcher again:")
print(f" python3 {sys.argv[0]}")
print("="*70 + "\n")
sys.exit(0)
except subprocess.CalledProcessError as e:
print("\n" + "="*70)
print("ERROR: Failed to install PyQt6")
print("="*70)
print(f"\nError: {e}")
print("\nPlease install manually:")
print(" python3 -m pip install PyQt6")
print("\nOr use a virtual environment:")
print(" python3 -m venv venv")
if sys.platform == "win32":
print(" venv\\Scripts\\activate")
else:
print(" source venv/bin/activate")
print(" pip install PyQt6")
print(f" python3 {sys.argv[0]}")
print("="*70 + "\n")
sys.exit(1)
# Import theme system (after PyQt6 is confirmed to be available)
try:
from client.ui.theme import get_app_stylesheet, get_theme_setting, save_theme_setting
except ImportError:
# Fallback if theme module not available
def get_app_stylesheet(theme="light"):
return ""
def get_theme_setting():
return "light"
def save_theme_setting(theme):
pass
# Status levels
class StatusLevel(Enum):
"""Status indicator levels."""
OK = "green"
WARNING = "yellow"
ERROR = "red"
UNKNOWN = "gray"
@dataclass
class CheckResult:
"""Result of a system check."""
name: str
status: StatusLevel
message: str
details: List[str]
fixable: bool = False
fix_command: Optional[str] = None
class LEDIndicator(QWidget):
"""Custom LED-style status indicator widget."""
clicked = pyqtSignal()
def __init__(self, label: str, parent=None):
super().__init__(parent)
self.label = label
self.status = StatusLevel.UNKNOWN
self.setMinimumSize(200, 60)
self.setCursor(Qt.CursorShape.PointingHandCursor)
def set_status(self, status: StatusLevel):
"""Update the LED status and repaint."""
self.status = status
self.update()
def paintEvent(self, event):
"""Draw the LED indicator."""
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
# Get theme-aware colors from palette
palette = self.palette()
bg_color = palette.color(palette.ColorRole.Base)
border_color = palette.color(palette.ColorRole.Mid)
text_color = palette.color(palette.ColorRole.Text)
# Draw widget background with border
painter.setPen(border_color)
painter.setBrush(bg_color)
painter.drawRoundedRect(0, 0, self.width()-1, self.height()-1, 6, 6)
# Draw LED circle
color = QColor(self.status.value)
painter.setBrush(color)
painter.setPen(Qt.PenStyle.NoPen)
painter.drawEllipse(15, 18, 24, 24)
# Add glow effect
glow_color = QColor(self.status.value)
glow_color.setAlpha(80)
painter.setBrush(glow_color)
painter.drawEllipse(12, 15, 30, 30)
# Draw LED border for definition
painter.setPen(text_color)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawEllipse(15, 18, 24, 24)
# Draw label
painter.setPen(text_color)
font = QFont()
font.setPointSize(10)
font.setBold(True)
painter.setFont(font)
painter.drawText(55, 33, self.label)
def mousePressEvent(self, event):
"""Handle click events."""
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
class CheckWorker(QThread):
"""Background worker for running system checks."""
progress = pyqtSignal(str)
finished = pyqtSignal(dict)
def __init__(self, check_type: str):
super().__init__()
self.check_type = check_type
def run(self):
"""Run the checks in background."""
results = {}
if self.check_type == "environment":
results = self.check_environment()
elif self.check_type == "system_deps":
results = self.check_system_dependencies()
elif self.check_type == "server_deps":
results = self.check_server_dependencies()
elif self.check_type == "client_deps":
results = self.check_client_dependencies()
elif self.check_type == "utils_deps":
results = self.check_utils_dependencies()
self.finished.emit(results)
def check_environment(self) -> Dict[str, CheckResult]:
"""Check Python environment."""
results = {}
# Python version
self.progress.emit("Checking Python version...")
version = sys.version_info
if version.major >= 3 and version.minor >= 8:
if version.minor >= 10:
results['python'] = CheckResult(
"Python Version",
StatusLevel.OK,
f"Python {version.major}.{version.minor}.{version.micro}",
[f"✓ Python {version.major}.{version.minor}.{version.micro} is excellent for LabLink"]
)
else:
results['python'] = CheckResult(
"Python Version",
StatusLevel.WARNING,
f"Python {version.major}.{version.minor}.{version.micro}",
[
f"⚠ Python {version.major}.{version.minor}.{version.micro} works but 3.10+ is recommended",
"Consider upgrading to Python 3.10 or higher for best performance"
]
)
else:
results['python'] = CheckResult(
"Python Version",
StatusLevel.ERROR,
f"Python {version.major}.{version.minor}.{version.micro} (too old)",
[
f"✗ Python {version.major}.{version.minor}.{version.micro} is not supported",
"LabLink requires Python 3.8 or higher",
"Please upgrade Python to continue"
],
fixable=False
)
# pip check
self.progress.emit("Checking pip...")
try:
result = subprocess.run(
[sys.executable, '-m', 'pip', '--version'],
capture_output=True,
text=True,
check=False
)
if result.returncode == 0:
pip_version = result.stdout.split()[1]
results['pip'] = CheckResult(
"pip",
StatusLevel.OK,
f"pip {pip_version}",
[f"✓ pip {pip_version} is installed"]
)
else:
results['pip'] = CheckResult(
"pip",
StatusLevel.ERROR,
"Not installed",
[
"✗ pip is not installed",
"Install with: python3 -m ensurepip --upgrade"
],
fixable=True,
fix_command="ensurepip"
)
except Exception as e:
results['pip'] = CheckResult(
"pip",
StatusLevel.ERROR,
"Error checking",
[f"✗ Error: {str(e)}"],
fixable=True,
fix_command="ensurepip"
)
# Virtual environment check
self.progress.emit("Checking virtual environment...")
in_venv = sys.prefix != sys.base_prefix
venv_paths = get_venv_paths()
venv_path = venv_paths['base']
if in_venv:
results['venv'] = CheckResult(
"Virtual Environment",
StatusLevel.OK,
"Active",
[
"✓ Running in virtual environment",
f" Path: {sys.prefix}"
]
)
elif venv_path.exists():
# Venv exists - this is good! The launcher uses it automatically
results['venv'] = CheckResult(
"Virtual Environment",
StatusLevel.OK,
"Available",
[
"✓ Virtual environment found",
f" Path: {venv_path.absolute()}",
" Note: The launcher automatically uses this venv",
" Manual activation not required for the launcher"
]
)
else:
results['venv'] = CheckResult(
"Virtual Environment",
StatusLevel.WARNING,
"Not created",
[
"⚠ No virtual environment found",
" Creating a venv is recommended for isolated dependencies",
" This launcher can create one for you"
],
fixable=True,
fix_command="create_venv"
)
# PEP 668 check
self.progress.emit("Checking for PEP 668...")
is_externally_managed = self._check_externally_managed()
if is_externally_managed and not in_venv and not venv_path.exists():
# Externally managed with no venv - this is a problem
results['pep668'] = CheckResult(
"Package Installation",
StatusLevel.WARNING,
"Externally managed",
[
"⚠ This is an externally-managed Python environment (PEP 668)",
" Ubuntu 24.04 and similar systems prevent system-wide pip installs",
" A virtual environment is strongly recommended",
" Or use: apt install python3-<package>"
]
)
elif is_externally_managed and (in_venv or venv_path.exists()):
# Externally managed but venv exists - this is OK, we handle it
results['pep668'] = CheckResult(
"Package Installation",
StatusLevel.OK,
"Handled via venv",
[
"✓ System is externally-managed (PEP 668)",
" This is normal for Ubuntu 24.04",
" The launcher uses the virtual environment to handle this",
" All package installations go to the venv"
]
)
else:
results['pep668'] = CheckResult(
"Package Installation",
StatusLevel.OK,
"Unrestricted",
["✓ Can install packages freely"]
)
return results
def check_system_dependencies(self) -> Dict[str, CheckResult]:
"""Check system-level dependencies."""
results = {}
os_type = platform.system()
self.progress.emit("Checking system dependencies...")
# Only check apt packages on Linux
if os_type == "Linux":
# Check if apt is available
if not self._check_command_exists('apt'):
results['system_packages'] = CheckResult(
"System Packages",
StatusLevel.WARNING,
"apt not found",
[
"⚠ apt package manager not found",
" System package checks are limited to Debian/Ubuntu-based systems"
]
)
return results
# Core system packages needed for LabLink
core_packages = [
"python3",
"python3-pip",
"python3-venv",
"git"
]
# Qt libraries for GUI
qt_packages = [
"libxcb-xinerama0",
"libxcb-icccm4",
"libxcb-keysyms1",
"libgl1" # Ubuntu 24.04: libgl1-mesa-glx replaced by libgl1
]
# USB libraries for equipment
usb_packages = [
"libusb-1.0-0"
]
# Build tools for Raspberry Pi image builder
build_packages = [
"kpartx", # Partition mapping for disk images
"qemu-user-static", # ARM emulation for chroot
"parted", # Partition manipulation
"wget", # Download utilities
"xz-utils" # Compression utilities
]
# Check all packages
all_packages = core_packages + qt_packages + usb_packages + build_packages
missing_packages = []
self.progress.emit("Checking system packages...")
for pkg in all_packages:
if not self._check_lib_installed(pkg):
missing_packages.append(pkg)
if not missing_packages:
results['system_packages'] = CheckResult(
"System Packages",
StatusLevel.OK,
"All installed",
[
"✓ All required system packages are installed",
f" Core: {', '.join(core_packages)}",
f" Qt: {', '.join(qt_packages)}",
f" USB: {', '.join(usb_packages)}",
f" Build tools: {', '.join(build_packages)}"
]
)
else:
# Categorize missing packages
missing_core = [p for p in missing_packages if p in core_packages]
missing_qt = [p for p in missing_packages if p in qt_packages]
missing_usb = [p for p in missing_packages if p in usb_packages]
missing_build = [p for p in missing_packages if p in build_packages]
status = StatusLevel.ERROR if missing_core else StatusLevel.WARNING
details = [
f"✗ {len(missing_packages)} system packages missing",
""
]
if missing_core:
details.append(f"Critical: {', '.join(missing_core)}")
if missing_qt:
details.append(f"Qt libraries: {', '.join(missing_qt)}")
if missing_usb:
details.append(f"USB support: {', '.join(missing_usb)}")
if missing_build:
details.append(f"Build tools (for Pi image builder): {', '.join(missing_build)}")
details.append("")
details.append("These packages can be installed automatically.")
results['system_packages'] = CheckResult(
"System Packages",
status,
f"{len(missing_packages)} missing",
details,
fixable=True,
fix_command=f"apt_install:{' '.join(missing_packages)}"
)
# VISA library check (optional)
visa_paths = [
'/usr/local/vxipnp/linux',
'/usr/lib/libvisa.so',
'/usr/local/lib/libvisa.so'
]
visa_found = any(Path(p).exists() for p in visa_paths)
if visa_found:
results['visa'] = CheckResult(
"NI-VISA",
StatusLevel.OK,
"Installed",
["✓ NI-VISA library found", " Hardware control available"]
)
else:
results['visa'] = CheckResult(
"NI-VISA",
StatusLevel.WARNING,
"Not installed",
[
"⚠ NI-VISA not detected (optional)",
" PyVISA-py (pure Python) will be used as fallback",
" For better performance, install from:",
" https://www.ni.com/en-us/support/downloads/drivers/download.ni-visa.html"
]
)
return results
def check_server_dependencies(self) -> Dict[str, CheckResult]:
"""Check server Python dependencies."""
results = {}
self.progress.emit("Checking server dependencies...")
req_file = Path("server/requirements.txt")
if not req_file.exists():
results['server_deps'] = CheckResult(
"Server Dependencies",
StatusLevel.ERROR,
"requirements.txt not found",
[
"✗ server/requirements.txt not found",
"Are you in the LabLink root directory?"
]
)
return results
packages = self._parse_requirements(req_file)
installed, missing = self._check_packages(packages)
if not missing:
results['server_deps'] = CheckResult(
"Server Dependencies",
StatusLevel.OK,
f"All installed ({len(installed)})",
[f"✓ All {len(installed)} server packages are installed"]
)
else:
results['server_deps'] = CheckResult(
"Server Dependencies",
StatusLevel.ERROR,
f"{len(missing)} missing",
[
f"✗ {len(missing)} packages missing: {', '.join(missing[:5])}{'...' if len(missing) > 5 else ''}",
f"Installed: {len(installed)}/{len(packages)}"
],
fixable=True,
fix_command="pip_install:server"
)
return results
def check_client_dependencies(self) -> Dict[str, CheckResult]:
"""Check client Python dependencies."""
results = {}
self.progress.emit("Checking client dependencies...")
req_file = Path("client/requirements.txt")
if not req_file.exists():
results['client_deps'] = CheckResult(
"Client Dependencies",
StatusLevel.ERROR,
"requirements.txt not found",
[
"✗ client/requirements.txt not found",
"Are you in the LabLink root directory?"
]
)
return results
packages = self._parse_requirements(req_file)
installed, missing = self._check_packages(packages)
if not missing:
results['client_deps'] = CheckResult(
"Client Dependencies",
StatusLevel.OK,
f"All installed ({len(installed)})",
[f"✓ All {len(installed)} client packages are installed"]
)
else:
results['client_deps'] = CheckResult(
"Client Dependencies",
StatusLevel.ERROR,
f"{len(missing)} missing",
[
f"✗ {len(missing)} packages missing: {', '.join(missing[:5])}{'...' if len(missing) > 5 else ''}",
f"Installed: {len(installed)}/{len(packages)}"
],
fixable=True,
fix_command="pip_install:client"
)
return results
def check_utils_dependencies(self) -> Dict[str, CheckResult]:
"""Check client utilities (deployment and discovery tools)."""
results = {}
self.progress.emit("Checking client utilities...")
# Utilities for deployment
deployment_utils = {
'paramiko': 'SSH client library for deployment',
'scp': 'SCP (secure copy) support',
}
# Utilities for network discovery
discovery_utils = {
'scapy': 'Network packet manipulation and discovery',
'zeroconf': 'mDNS/Bonjour service discovery',
}
all_utils = {**deployment_utils, **discovery_utils}
# Check which utilities are installed
installed = []
missing = []
# Map package names to import names for special cases
package_to_import = {
'python-dotenv': 'dotenv',
'python-dateutil': 'dateutil',
'pydantic-settings': 'pydantic_settings',
'pyserial': 'serial',
'pyusb': 'usb',
'PyJWT': 'jwt',
}
# Determine which Python to use for checking
venv_paths = get_venv_paths()
venv_python = venv_paths['python']
use_venv = venv_python.exists()
for pkg, description in all_utils.items():
# Get the correct import name
import_name = package_to_import.get(pkg, pkg.replace("-", "_"))
if use_venv:
# Check if package is installed in venv using subprocess
result = subprocess.run(
[str(venv_python), '-c', f'import {import_name}'],
capture_output=True,
check=False
)
if result.returncode == 0:
installed.append(pkg)
else:
missing.append(pkg)
else:
# Check if package is installed in current environment
try:
__import__(import_name)
installed.append(pkg)
except ImportError:
missing.append(pkg)
# Determine status
if not missing:
results['utils_deps'] = CheckResult(
"Client Utilities",
StatusLevel.OK,
f"All installed ({len(installed)})",
[
f"✓ All {len(installed)} utilities are installed",
"",
"Deployment utilities:",
*[f" ✓ {pkg}: {deployment_utils[pkg]}" for pkg in deployment_utils if pkg in installed],
"",
"Discovery utilities:",
*[f" ✓ {pkg}: {discovery_utils[pkg]}" for pkg in discovery_utils if pkg in installed],
]
)
else:
# Categorize missing utilities
missing_deployment = [p for p in missing if p in deployment_utils]
missing_discovery = [p for p in missing if p in discovery_utils]
details = [
f"✗ {len(missing)} utilities missing",
"",
]
if missing_deployment:
details.append("Missing deployment utilities:")
for pkg in missing_deployment:
details.append(f" ✗ {pkg}: {deployment_utils[pkg]}")
details.append("")
if missing_discovery:
details.append("Missing discovery utilities:")
for pkg in missing_discovery:
details.append(f" ✗ {pkg}: {discovery_utils[pkg]}")
details.append("")
if installed:
details.append(f"Installed: {len(installed)}/{len(all_utils)}")
details.append("")
details.append("These utilities can be installed automatically.")
results['utils_deps'] = CheckResult(
"Client Utilities",
StatusLevel.ERROR,
f"{len(missing)} missing",
details,
fixable=True,
fix_command="pip_install:client_utils"
)
return results
def _check_externally_managed(self) -> bool:
"""Check if Python is externally managed (PEP 668)."""
if sys.prefix != sys.base_prefix:
return False
import sysconfig
stdlib = sysconfig.get_path('stdlib')
if stdlib:
marker = Path(stdlib) / 'EXTERNALLY-MANAGED'
return marker.exists()
return False
def _check_command_exists(self, command: str) -> bool:
"""Check if a command exists in PATH."""
try:
result = subprocess.run(
['which', command],
capture_output=True,
text=True,
check=False
)
return result.returncode == 0
except FileNotFoundError:
return False
def _check_lib_installed(self, lib_name: str) -> bool:
"""Check if a system library/package is installed (dpkg)."""
try:
result = subprocess.run(
['dpkg', '-s', lib_name],
capture_output=True,
text=True,
check=False
)
return result.returncode == 0
except FileNotFoundError:
return False
def _parse_requirements(self, req_file: Path) -> List[str]:
"""Parse requirements.txt file."""
packages = []
for line in req_file.read_text().splitlines():
line = line.strip()
if line and not line.startswith('#'):
# Extract package name
pkg = line.split('>=')[0].split('==')[0].split('[')[0]
packages.append(pkg)
return packages
def _check_packages(self, packages: List[str]) -> Tuple[List[str], List[str]]:
"""Check which packages are installed (optimized batch check).
If a venv exists, checks packages in the venv.
Otherwise, checks packages in the current environment.
"""
installed = []
missing = []
# Map package names to import names for special cases
package_to_import = {
'python-dotenv': 'dotenv',
'python-dateutil': 'dateutil',
'pydantic-settings': 'pydantic_settings',
'uvicorn': 'uvicorn',
'pyvisa-py': 'pyvisa_py',
'PyQt6-Qt6': 'PyQt6', # PyQt6-Qt6 is just Qt binaries, check PyQt6 instead
'PyQt6-Charts': 'PyQt6.QtCharts', # PyQt6-Charts imports as PyQt6.QtCharts
'PyQt6-Charts-Qt6': 'PyQt6.QtCharts', # PyQt6-Charts-Qt6 is just binaries, check PyQt6.QtCharts instead
'pyserial': 'serial', # pyserial package imports as 'serial'
'pyusb': 'usb', # pyusb package imports as 'usb'
'PyJWT': 'jwt', # PyJWT package imports as 'jwt'
'email-validator': 'email_validator', # email-validator imports as 'email_validator'
}
# Determine which Python to use for checking
venv_paths = get_venv_paths()
venv_python = venv_paths['python']
use_venv = venv_python.exists()
logger.debug(f"Checking {len(packages)} packages, use_venv={use_venv}, venv_python={venv_python}")
if use_venv:
# OPTIMIZED: Check all packages in a single subprocess call
# Build a proper multiline Python script
import_checks = []
for pkg in packages:
import_name = package_to_import.get(pkg, pkg.replace("-", "_"))
import_checks.append((pkg, import_name))
# Create a properly formatted multiline script
batch_check = "import sys\nresults = {}\n"
for pkg, import_name in import_checks:
# Use proper multiline try/except blocks
batch_check += f"try:\n"
# Handle dotted imports (e.g., 'PyQt6.QtCharts') correctly
if '.' in import_name:
# For dotted imports, use fromlist to actually import the submodule
parts = import_name.rsplit('.', 1)
batch_check += f" __import__('{import_name}', fromlist=['{parts[1]}'])\n"
else:
batch_check += f" __import__('{import_name}')\n"
batch_check += f" results['{pkg}'] = 'OK'\n"
batch_check += f"except Exception:\n"
batch_check += f" results['{pkg}'] = 'MISS'\n"
batch_check += "print('|'.join(f'{k}={v}' for k, v in results.items()))\n"
result = subprocess.run(
[str(venv_python), '-c', batch_check],
capture_output=True,
text=True,
check=False
)
if result.returncode == 0 and result.stdout.strip():
# Parse batch results
for item in result.stdout.strip().split('|'):
if '=' in item:
pkg, status = item.split('=', 1)
if status == 'OK':
installed.append(pkg)
logger.debug(f" {pkg}: INSTALLED")
else:
missing.append(pkg)
logger.debug(f" {pkg}: MISSING")
else:
# Fallback: if batch check fails, assume all missing
logger.warning("Batch package check failed, marking all as missing")
missing.extend(packages)
else:
# Check in current environment (also batched)
for pkg in packages:
import_name = package_to_import.get(pkg, pkg.replace("-", "_"))
try:
__import__(import_name)
logger.debug(f" {pkg}: INSTALLED (system environment)")
installed.append(pkg)
except ImportError:
logger.debug(f" {pkg}: MISSING (system environment)")
missing.append(pkg)
logger.debug(f"Package check complete: {len(installed)} installed, {len(missing)} missing")
return installed, missing
class FixWorker(QThread):
"""Background worker for applying fixes."""
progress_update = pyqtSignal(str, int) # message, progress value
fix_error = pyqtSignal(str, str) # issue name, error message
finished = pyqtSignal()
def __init__(self, issues: List[CheckResult], parent_launcher):
super().__init__()
self.issues = issues
self.launcher = parent_launcher
def run(self):