-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwin_device_manager.py
More file actions
1215 lines (1034 loc) · 51.3 KB
/
win_device_manager.py
File metadata and controls
1215 lines (1034 loc) · 51.3 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
"""
LinMan - Linux Device Manager (Complete Edition)
A native, standalone device manager for hardware diagnostics.
Dependencies:
pip install PySide6 pyudev
Features:
- Privilege Levels: Starts as User. Switch to Root via toolbar.
- Stability: Uses Handshake logic to ensure smooth User -> Root transition.
- Monitors: Native EDID parsing for real model names.
- RAM: DMI decoding (Root only).
- Interface: Windows Device Manager look & feel.
"""
import sys
import socket
import os
import re
import subprocess
import shlex
import shutil
import tempfile
import time
import logging
import fcntl
import atexit
from dataclasses import dataclass, field
from PySide6.QtWidgets import (QApplication, QMainWindow, QTreeWidget, QTreeWidgetItem,
QMessageBox, QVBoxLayout, QWidget, QDialog, QLabel,
QFormLayout, QToolBar, QStyle, QTabWidget, QGroupBox,
QLineEdit, QTextEdit, QFrame, QMenu, QMenuBar, QStatusBar,
QDialogButtonBox, QHBoxLayout, QPushButton, QComboBox,
QSizePolicy)
from PySide6.QtCore import Qt, QSize, QSocketNotifier, Slot, QTimer, QThread, Signal
from PySide6.QtGui import QIcon, QAction, QFont, QPainter, QPixmap, QKeySequence, QShortcut
import pyudev
# --- LOGGING ---
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
log = logging.getLogger("LinMan")
# --- CONFIGURATION ---
GITHUB_URL = "https://github.com/lolren/LinMan-Linux-Device-Manager"
VERSION = "1.3.8"
HANDSHAKE_FILE = os.path.join(tempfile.gettempdir(), "linman_root_active.lock")
# --- Virtual Device dataclass ---
@dataclass
class VirtualDevice:
"""Represents a non-udev device (monitors, RAM, CPUs)."""
sys_name: str
sys_path: str
device_path: str
properties: dict = field(default_factory=dict)
# --- Backend: EDID Parser (Monitors) ---
class EdidParser:
@staticmethod
def get_monitor_name(sys_path):
"""Reads binary EDID data from sysfs to get the real monitor model name."""
edid_path = os.path.join(sys_path, "edid")
if not os.path.exists(edid_path): return None
try:
with open(edid_path, 'rb') as f:
edid = f.read()
if len(edid) < 128: return None
# Walk through the 4 descriptors in the EDID block
for i in [54, 72, 90, 108]:
# Monitor Name tag is 0xFC
if edid[i:i+4] == b'\x00\x00\x00\xfc':
text = edid[i+5:i+18].decode('cp437', 'ignore').split('\x0a')[0]
return text.strip()
except (OSError, IOError, ValueError) as e:
log.debug("Failed to parse EDID at %s: %s", sys_path, e)
return None
# --- Backend: DMI Parser (RAM) ---
class DmiParser:
"""
Handles 'dmidecode' to read RAM stick info.
Strictly checks for root.
"""
@staticmethod
def get_ram_modules():
if os.geteuid() != 0:
return []
modules = []
try:
cmd = ['dmidecode', '-t', '17']
output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode('utf-8')
current_stick = {}
for line in output.splitlines():
line = line.strip()
if "Memory Device" in line:
if current_stick: modules.append(current_stick)
current_stick = {'Name': 'Unknown RAM', 'Size': 'Unknown', 'Type': 'Unknown', 'Speed': 'Unknown'}
elif not current_stick:
continue
if ":" in line:
k, v = [x.strip() for x in line.split(':', 1)]
if k == "Size": current_stick['Size'] = v
elif k == "Type": current_stick['Type'] = v
elif k == "Speed": current_stick['Speed'] = v
elif k == "Manufacturer": current_stick['Manufacturer'] = v
elif k == "Part Number": current_stick['Part'] = v
elif k == "Locator": current_stick['Slot'] = v
if current_stick: modules.append(current_stick)
except (OSError, subprocess.CalledProcessError, FileNotFoundError) as e:
log.warning("dmidecode failed: %s", e)
return modules
# --- Backend: Native System Resolver ---
class SystemResolver:
"""Resolves PCI IDs to human readable names using lspci."""
def __init__(self):
self.has_lspci = shutil.which('lspci') is not None
self.pci_cache = {}
def invalidate_cache(self):
self.pci_cache.clear()
def get_pci_name(self, pci_slot_name):
if not self.has_lspci or not pci_slot_name: return None, None
if pci_slot_name in self.pci_cache: return self.pci_cache[pci_slot_name]
try:
output = subprocess.check_output(
['lspci', '-s', pci_slot_name, '-vmm'],
stderr=subprocess.DEVNULL
).decode('utf-8')
vendor = None
device = None
for line in output.splitlines():
if line.startswith('Vendor:'): vendor = line.split(':', 1)[1].strip()
elif line.startswith('Device:'): device = line.split(':', 1)[1].strip()
self.pci_cache[pci_slot_name] = (vendor, device)
return vendor, device
except (OSError, subprocess.CalledProcessError) as e:
log.debug("lspci failed for %s: %s", pci_slot_name, e)
return None, None
# --- Helper: Icon Factory ---
class IconFactory:
"""Handles loading icons from the Linux theme or internal fallbacks."""
@staticmethod
def get(name_list, fallback_style_standard):
for name in name_list:
if QIcon.hasThemeIcon(name): return QIcon.fromTheme(name)
return QApplication.style().standardIcon(fallback_style_standard)
@staticmethod
def apply_overlay(base_icon, mode='normal'):
"""Adds Ghost (transparent) or Warning (Yellow !) overlays."""
pixmap = base_icon.pixmap(32, 32)
target = QPixmap(pixmap.size())
target.fill(Qt.transparent)
painter = QPainter(target)
if mode == 'ghost':
painter.setOpacity(0.5)
painter.drawPixmap(0, 0, pixmap)
else:
painter.drawPixmap(0, 0, pixmap)
if mode == 'warning':
# Draw yellow bang in bottom right
warn_icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning).pixmap(16, 16)
painter.drawPixmap(16, 16, warn_icon)
painter.end()
return QIcon(target)
# --- Worker: Background device enumeration ---
class DeviceEnumerator(QThread):
"""Enumerates devices in a background thread to avoid blocking the UI."""
finished = Signal(dict)
def __init__(self, context, resolver, is_root):
super().__init__()
self.context = context
self.resolver = resolver
self.is_root = is_root
def run(self):
unique_devices = {}
try:
self._enumerate(unique_devices)
except Exception as e:
log.error("Device enumeration failed: %s", e)
self.finished.emit(unique_devices)
def _enumerate(self, unique_devices):
# Track device paths claimed by specific subsystem scans (cameras, bluetooth, etc.)
# so we can avoid duplicating them under generic USB controllers
claimed_usb_ancestors = set()
# --- 1. Base Hardware (PCI) ---
for device in self.context.list_devices(subsystem='pci'):
ven = device.properties.get('ID_VENDOR_FROM_DATABASE')
dev = device.properties.get('ID_MODEL_FROM_DATABASE')
if not ven or not dev:
ven, dev = self.resolver.get_pci_name(device.sys_name)
if not ven: ven = device.properties.get('ID_VENDOR_ID', 'Unknown Vendor')
if not dev: dev = device.properties.get('ID_MODEL_ID', 'Unknown Device')
cat = self._determine_pci_category(device)
driver = device.properties.get('DRIVER', '')
self._add_entry(unique_devices, device, dev, ven, cat, 'pci', driver)
# --- 3. Cameras (Webcams) --- (before USB so we can claim their ancestors)
seen_cameras = set()
for device in self.context.list_devices(subsystem='video4linux'):
if not device.sys_name.startswith('video'): continue
# Deduplicate by parent path (one camera can expose multiple /dev/videoN nodes)
parent_path = device.parent.device_path if device.parent else device.device_path
if parent_path in seen_cameras: continue
seen_cameras.add(parent_path)
# Walk up to the USB parent to get the real product name from the hwdb
name = None
vendor = None
curr = device
for _ in range(5):
if curr is None: break
name = name or curr.properties.get('ID_MODEL_FROM_DATABASE')
vendor = vendor or curr.properties.get('ID_VENDOR_FROM_DATABASE')
# Mark USB ancestors as claimed
if curr.subsystem == 'usb' and getattr(curr, 'device_type', None) == 'usb_device':
claimed_usb_ancestors.add(curr.device_path)
if name and vendor: break
curr = curr.parent
if not name: name = device.properties.get('ID_V4L_PRODUCT', device.properties.get('ID_MODEL', 'Webcam')).replace('_', ' ')
if not vendor: vendor = device.properties.get('ID_VENDOR', 'Generic').replace('_', ' ')
driver, _ = self._get_driver_recursive(device)
self._add_entry(unique_devices, device, name, vendor, 'Cameras', 'video4linux', driver)
# --- Pre-scan: Claim USB ancestors for bluetooth ---
for device in self.context.list_devices(subsystem='bluetooth'):
if 'hci' in device.sys_name:
curr = device
for _ in range(5):
curr = curr.parent if curr else None
if curr and curr.subsystem == 'usb' and getattr(curr, 'device_type', None) == 'usb_device':
claimed_usb_ancestors.add(curr.device_path)
break
# --- 2. USB --- (skip devices already claimed by cameras/bluetooth)
for device in self.context.list_devices(subsystem='usb'):
if device.device_type == 'usb_device':
if device.device_path in claimed_usb_ancestors:
continue
ven = device.properties.get('ID_VENDOR_FROM_DATABASE', device.properties.get('ID_VENDOR', 'USB Vendor'))
dev = device.properties.get('ID_MODEL_FROM_DATABASE', device.properties.get('ID_MODEL', 'USB Device'))
driver, _ = self._get_driver_recursive(device)
self._add_entry(unique_devices, device, dev, ven, 'Universal Serial Bus controllers', 'usb', driver)
# --- 4. Monitors (DRM EDID) ---
drm_path = "/sys/class/drm"
if os.path.exists(drm_path):
for conn in os.listdir(drm_path):
if "-" in conn and os.path.exists(f"{drm_path}/{conn}/status"):
try:
with open(f"{drm_path}/{conn}/status") as f: status = f.read().strip()
if status == "connected":
real_name = EdidParser.get_monitor_name(f"{drm_path}/{conn}")
if not real_name: real_name = f"Generic Monitor ({conn})"
card_path = os.path.realpath(f"{drm_path}/{conn}")
fake_device = VirtualDevice(sys_name=conn, sys_path=card_path, device_path=card_path)
self._add_entry(unique_devices, fake_device, real_name, "Standard Monitor Types", "Monitors", "drm", "monitor-driver")
except (OSError, IOError) as e:
log.debug("Failed to read DRM connector %s: %s", conn, e)
# --- 5. Memory (RAM) ---
ram_modules = DmiParser.get_ram_modules()
if ram_modules:
for i, mod in enumerate(ram_modules):
if "No Module" in mod.get('Size', ''): continue
name = f"{mod.get('Size')} {mod.get('Type')} {mod.get('Speed')}"
path = f"/sys/devices/system/memory/stick_{i}"
fake_mem = VirtualDevice(sys_name=f'ram_{i}', sys_path=path, device_path=path)
self._add_entry(unique_devices, fake_mem, name, mod.get('Manufacturer', 'Unknown'), "Memory (RAM Sticks)", "memory", "ram")
else:
try:
with open('/proc/meminfo') as f:
total_mem = next((line.split(':')[1].strip() for line in f if "MemTotal" in line), "Unknown")
try:
kb = int(total_mem.split()[0])
gb = kb / (1024 * 1024)
mem_str = f"{gb:.1f} GB"
except (ValueError, IndexError):
mem_str = total_mem
fake_mem = VirtualDevice(sys_name='mem_sys', sys_path='/sys/devices/system/memory', device_path='/sys/devices/system/memory/ram')
label = f"System Memory ({mem_str})"
vendor_hint = "System" if self.is_root else "System (Switch to Root for details)"
self._add_entry(unique_devices, fake_mem, label, vendor_hint, "Memory (RAM Sticks)", "memory", "ram")
except (OSError, IOError) as e:
log.warning("Failed to read /proc/meminfo: %s", e)
# --- 6. Subsystems ---
for device in self.context.list_devices(subsystem='drm'):
if device.parent and device.parent.device_path in unique_devices:
unique_devices[device.parent.device_path]['category'] = 'Display adapters'
for device in self.context.list_devices(subsystem='net'):
self._handle_child(unique_devices, device, 'Network adapters')
for device in self.context.list_devices(subsystem='sound'):
if 'card' in device.sys_name:
curr = device
while curr.parent:
curr = curr.parent
if curr.device_path in unique_devices:
unique_devices[curr.device_path]['category'] = 'Sound, video and game controllers'
break
for device in self.context.list_devices(subsystem='block'):
if device.device_type == 'disk':
self._handle_child(unique_devices, device, 'Disk drives', force_new=True)
for device in self.context.list_devices(subsystem='bluetooth'):
if 'hci' in device.sys_name:
driver, _ = self._get_driver_recursive(device)
if device.parent and device.parent.device_path in unique_devices:
unique_devices[device.parent.device_path]['category'] = 'Bluetooth'
unique_devices[device.parent.device_path]['name'] = 'Bluetooth Adapter'
else:
name = 'Bluetooth Adapter'
vendor = 'Generic'
curr = device
for _ in range(5):
curr = curr.parent if curr else None
if curr and curr.subsystem in ['usb', 'usb_device', 'pci']:
name = (curr.properties.get('ID_MODEL_FROM_DATABASE') or
curr.properties.get('ID_MODEL') or
curr.properties.get('product', 'Bluetooth Adapter'))
vendor = (curr.properties.get('ID_VENDOR_FROM_DATABASE') or
curr.properties.get('ID_VENDOR') or
curr.properties.get('manufacturer', 'Generic'))
break
name = name.replace('_', ' ')
self._add_entry(unique_devices, device, name, vendor, 'Bluetooth', 'bluetooth', driver)
for device in self.context.list_devices(subsystem='tty'):
self._handle_child(unique_devices, device, 'Ports (COM & LPT)', force_new=True, fmt="Communications Port ({})")
for device in self.context.list_devices(subsystem='input'):
if device.sys_name.startswith('input'):
props = device.properties
cat = None
if props.get('ID_INPUT_KEYBOARD') == '1': cat = 'Keyboards'
elif props.get('ID_INPUT_MOUSE') == '1': cat = 'Mice and other pointing devices'
if cat:
name = props.get('NAME', 'Input Device').strip('"')
driver, _ = self._get_driver_recursive(device)
self._add_entry(unique_devices, device, name, '', cat, 'input', driver)
for device in self.context.list_devices(subsystem='power_supply'):
if device.properties.get('POWER_SUPPLY_TYPE') == 'Battery':
# Gather battery details from sysfs properties
props = device.properties
bat_details = {}
for key in ('POWER_SUPPLY_STATUS', 'POWER_SUPPLY_CAPACITY', 'POWER_SUPPLY_HEALTH',
'POWER_SUPPLY_TECHNOLOGY', 'POWER_SUPPLY_VOLTAGE_NOW',
'POWER_SUPPLY_ENERGY_FULL_DESIGN', 'POWER_SUPPLY_ENERGY_FULL',
'POWER_SUPPLY_CYCLE_COUNT', 'POWER_SUPPLY_MODEL_NAME',
'POWER_SUPPLY_MANUFACTURER'):
val = props.get(key)
if val:
bat_details[key] = val
bat_name = bat_details.get('POWER_SUPPLY_MODEL_NAME', device.sys_name)
bat_vendor = bat_details.get('POWER_SUPPLY_MANUFACTURER', '')
capacity = bat_details.get('POWER_SUPPLY_CAPACITY')
status = bat_details.get('POWER_SUPPLY_STATUS', '')
label = f"Battery: {bat_name}"
if capacity:
label += f" ({capacity}%"
if status and status != 'Unknown':
label += f", {status}"
label += ")"
entry = self._add_entry(unique_devices, device, label, bat_vendor, 'Batteries', 'power', 'battery')
# Stash battery details for the properties dialog
if device.device_path in unique_devices:
unique_devices[device.device_path]['battery_details'] = bat_details
# Processors
try:
with open('/proc/cpuinfo') as f:
model = next((line.split(':')[1].strip() for line in f if "model name" in line), "Processor")
for i in range(os.cpu_count() or 1):
path = f"/sys/devices/system/cpu/cpu{i}"
fake_dev = VirtualDevice(sys_name=f'cpu{i}', sys_path=path, device_path=path)
self._add_entry(unique_devices, fake_dev, model, 'Intel/AMD', 'Processors', 'cpu', 'processor')
except (OSError, IOError) as e:
log.warning("Failed to read /proc/cpuinfo: %s", e)
def _get_device_status_flags(self, device, category):
name = device.sys_name
sys_path = device.sys_path
is_hidden = False
is_physical = True
if '/virtual/' in sys_path:
is_physical = False
is_hidden = True
if category == 'Ports (COM & LPT)':
if name.startswith(('ttyUSB', 'ttyACM')): is_hidden = False
else: is_hidden = True
if category == 'Network adapters':
if name == 'lo': is_hidden = True
if any(x in name for x in ['virbr', 'docker', 'veth', 'tun', 'tap', 'tailscale', 'wg']):
is_hidden = True
is_physical = False
if category == 'Disk drives':
if name.startswith(('loop', 'ram', 'dm-')):
is_hidden = True
is_physical = False
if category == 'Monitors' or category == 'Memory':
is_physical = True
is_hidden = False
return is_hidden, is_physical
def _get_driver_recursive(self, device):
driver = device.properties.get('DRIVER', '')
if driver: return driver, False
curr = device
steps = 0
while curr.parent and steps < 4:
curr = curr.parent
driver = curr.properties.get('DRIVER', '')
if driver and driver != 'pcieport':
return f"{driver} (via parent)", True
steps += 1
return '', False
def _add_entry(self, db, device, name, vendor, cat, sub, driver):
is_hidden, is_physical = self._get_device_status_flags(device, cat)
db[device.device_path] = {
'name': name, 'vendor': vendor, 'category': cat,
'sys_path': device.sys_path, 'subsystem': sub,
'driver': driver, 'is_hidden': is_hidden, 'is_physical': is_physical,
'devpath': device.device_path
}
def _handle_child(self, db, device, category, force_new=False, fmt="{}"):
driver, _ = self._get_driver_recursive(device)
if not force_new:
curr = device
found_parent = False
for _ in range(3):
parent = curr.parent
if parent and parent.device_path in db:
db[parent.device_path]['category'] = category
if not db[parent.device_path]['driver'] and driver:
db[parent.device_path]['driver'] = driver
found_parent = True
break
if parent: curr = parent
else: break
if found_parent: return
# Try to get a better name from parent hwdb for block devices
name = None
if category == 'Disk drives':
curr = device
for _ in range(5):
if curr is None: break
name = curr.properties.get('ID_MODEL_FROM_DATABASE')
if name: break
curr = curr.parent
if not name:
name = device.properties.get('ID_MODEL', device.sys_name).replace('_', ' ')
else:
name = name.replace('_', ' ')
if fmt != "{}": name = fmt.format(device.sys_name)
vendor = device.properties.get('ID_VENDOR_FROM_DATABASE', device.properties.get('ID_VENDOR', '')).replace('_', ' ')
self._add_entry(db, device, name, vendor, category, device.subsystem, driver)
def _determine_pci_category(self, device):
pci_class = device.properties.get('PCI_CLASS')
if not pci_class:
try:
with open(f"{device.sys_path}/class", 'r') as f: pci_class = f.read().strip()
except (OSError, IOError):
pass
if not pci_class: return 'System devices'
code = pci_class.lower().replace('0x', '').zfill(6)[0:2]
mapping = {
'00': 'Other devices', '01': 'Storage controllers', '02': 'Network adapters',
'03': 'Display adapters', '04': 'Sound, video and game controllers',
'05': 'Memory Controllers (System)',
'06': 'System devices',
'07': 'Communication controllers', '08': 'System devices',
'09': 'Input devices', '0c': 'Universal Serial Bus controllers'
}
return mapping.get(code, 'System devices')
# --- UI: Properties Dialog ---
class PropertiesDialog(QDialog):
def __init__(self, device_data, icon, parent=None):
super().__init__(parent)
self.device_data = device_data
self.icon = icon
self.setWindowTitle(f"Properties: {self.device_data.get('MODEL')}")
self.setMinimumSize(600, 600)
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self.setup_ui()
def setup_ui(self):
layout = QVBoxLayout()
layout.setContentsMargins(15, 15, 15, 15)
# Header with Icon and Big Name
header_layout = QHBoxLayout()
icon_label = QLabel()
icon_label.setPixmap(self.icon.pixmap(64, 64))
name_text = self.device_data.get('MODEL', 'Unknown Device')
name_label = QLabel(f"<b>{name_text}</b>")
name_label.setStyleSheet("font-size: 14pt; font-weight: bold;")
name_label.setWordWrap(True)
header_layout.addWidget(icon_label)
header_layout.addWidget(name_label)
header_layout.addStretch()
layout.addLayout(header_layout)
# Tabs
self.tabs = QTabWidget()
self.tabs.addTab(self.create_general_tab(), "General")
self.tabs.addTab(self.create_driver_tab(), "Driver")
self.tabs.addTab(self.create_details_tab(), "Details")
layout.addWidget(self.tabs)
# Close Button
button_box = QDialogButtonBox(QDialogButtonBox.Close)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.setLayout(layout)
def create_general_tab(self):
widget = QWidget()
layout = QVBoxLayout()
info_group = QGroupBox("Device Information")
info_layout = QFormLayout()
info_layout.addRow("Device Type:", QLabel(self.device_data.get('CATEGORY', 'Unknown')))
info_layout.addRow("Manufacturer:", QLabel(self.device_data.get('VENDOR', 'Unknown')))
info_layout.addRow("Location:", QLabel(os.path.basename(self.device_data.get('SYS_PATH', 'Unknown'))))
# Battery-specific details
bat = self.device_data.get('BATTERY_DETAILS')
if bat:
info_layout.addRow("", self._create_separator())
if bat.get('POWER_SUPPLY_TECHNOLOGY'):
info_layout.addRow("Technology:", QLabel(bat['POWER_SUPPLY_TECHNOLOGY']))
if bat.get('POWER_SUPPLY_CAPACITY'):
info_layout.addRow("Charge:", QLabel(f"{bat['POWER_SUPPLY_CAPACITY']}%"))
if bat.get('POWER_SUPPLY_STATUS'):
info_layout.addRow("Status:", QLabel(bat['POWER_SUPPLY_STATUS']))
if bat.get('POWER_SUPPLY_HEALTH'):
info_layout.addRow("Health:", QLabel(bat['POWER_SUPPLY_HEALTH']))
if bat.get('POWER_SUPPLY_CYCLE_COUNT'):
info_layout.addRow("Cycle Count:", QLabel(bat['POWER_SUPPLY_CYCLE_COUNT']))
# Show wear level if both design and current capacity are available
design = bat.get('POWER_SUPPLY_ENERGY_FULL_DESIGN')
current = bat.get('POWER_SUPPLY_ENERGY_FULL')
if design and current:
try:
d = int(design)
c = int(current)
if d > 0:
wear_pct = ((d - c) / d) * 100
info_layout.addRow("Wear Level:", QLabel(f"{wear_pct:.1f}%"))
except (ValueError, ZeroDivisionError):
pass
if bat.get('POWER_SUPPLY_VOLTAGE_NOW'):
try:
uv = int(bat['POWER_SUPPLY_VOLTAGE_NOW'])
info_layout.addRow("Voltage:", QLabel(f"{uv / 1_000_000:.2f} V"))
except ValueError:
pass
info_group.setLayout(info_layout)
layout.addWidget(info_group)
status_group = QGroupBox("Device Status")
status_layout = QVBoxLayout()
status_text = QTextEdit()
driver = self.device_data.get('DRIVER')
is_hidden = self.device_data.get('IS_HIDDEN', False)
is_physical = self.device_data.get('IS_PHYSICAL', True)
category = self.device_data.get('CATEGORY', '')
msg = []
if not is_physical:
msg.append("This is a Virtual/System device.")
if is_hidden: msg.append("It is hidden by default.")
elif is_hidden:
msg.append("This device is currently disconnected or hidden.")
if driver:
msg.append("This device is working properly.")
msg.append(f"Driver loaded: {driver}")
elif is_physical and not driver:
# FIX: Don't show error for System Resources
if category in ['Memory Controllers (System)', 'System devices', 'Processors']:
msg.append("This device is working properly.")
msg.append("No driver is required for this system resource.")
else:
msg.append("The drivers for this device are not installed. (Code 28)")
msg.append("No kernel module is currently bound to this hardware.")
else:
msg.append("No driver required.")
status_text.setPlainText("\n".join(msg))
status_text.setReadOnly(True)
status_text.setMaximumHeight(100)
status_text.setStyleSheet("border: 1px solid palette(mid);")
status_layout.addWidget(status_text)
status_group.setLayout(status_layout)
layout.addStretch()
widget.setLayout(layout)
return widget
def create_driver_tab(self):
widget = QWidget()
layout = QVBoxLayout()
driver_group = QGroupBox("Driver")
driver_layout = QFormLayout()
driver_name = self.device_data.get('DRIVER', 'None')
clean_driver_name = driver_name.split(' ')[0] if driver_name else None
driver_layout.addRow("Kernel Module:", QLabel(f"<b>{driver_name}</b>"))
driver_group.setLayout(driver_layout)
layout.addWidget(driver_group)
# Admin Actions
actions_group = QGroupBox("Actions (Root Required)")
actions_layout = QVBoxLayout()
btn_unbind = QPushButton(f"Unbind Driver")
btn_unbind.clicked.connect(lambda: self.action_unbind(clean_driver_name))
btn_reprobe = QPushButton("Rescan/Reprobe")
btn_reprobe.clicked.connect(self.action_reprobe)
btn_unload = QPushButton(f"Unload Module (modprobe -r)")
btn_unload.clicked.connect(lambda: self.action_unload_module(clean_driver_name))
is_root = (os.geteuid() == 0)
# Disable logic
if not clean_driver_name or clean_driver_name == 'None':
btn_unbind.setEnabled(False)
btn_unload.setEnabled(False)
if not is_root:
btn_unbind.setEnabled(False)
btn_reprobe.setEnabled(False)
btn_unload.setEnabled(False)
actions_layout.addWidget(QLabel("<i>Relaunch in Root Mode to use these features.</i>"))
actions_layout.addWidget(btn_unbind)
actions_layout.addWidget(btn_reprobe)
actions_layout.addWidget(self._create_separator())
actions_layout.addWidget(btn_unload)
actions_group.setLayout(actions_layout)
layout.addWidget(actions_group)
layout.addStretch()
widget.setLayout(layout)
return widget
@staticmethod
def _create_separator():
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
return line
# Keep old name for compatibility
def create_separator(self):
return self._create_separator()
def create_details_tab(self):
widget = QWidget()
layout = QVBoxLayout()
layout.addWidget(QLabel("Property:"))
combo = QComboBox()
combo.addItems(["SysFS Path", "Device Path", "Subsystem", "Driver", "Attributes"])
val_text = QTextEdit()
val_text.setReadOnly(True)
val_text.setFont(QFont("Monospace"))
def update_text(idx):
keys = ['SYS_PATH', 'DEVPATH', 'SUBSYSTEM', 'DRIVER']
if idx < 4:
val_text.setText(str(self.device_data.get(keys[idx], '')))
else:
val_text.setText(str(self.device_data))
combo.currentIndexChanged.connect(update_text)
update_text(0)
layout.addWidget(combo)
layout.addWidget(QLabel("Value:"))
layout.addWidget(val_text)
widget.setLayout(layout)
return widget
def run_root_command(self, cmd_args):
"""Execute a command as root. cmd_args must be a list of arguments (no shell)."""
if os.geteuid() != 0:
QMessageBox.warning(self, "Permission Denied", "You must run LinMan in Root Mode to perform this action.")
return
try:
log.info("Executing root command: %s", cmd_args)
subprocess.check_call(cmd_args)
QMessageBox.information(self, "Success", "Command executed.")
except subprocess.CalledProcessError as e:
log.error("Root command failed: %s", e)
QMessageBox.warning(self, "Error", "Action failed.")
def action_unbind(self, driver):
subsystem = self.device_data.get('SUBSYSTEM')
sys_path = self.device_data.get('SYS_PATH', '')
device_name = os.path.basename(sys_path)
unbind_path = f"/sys/bus/{subsystem}/drivers/{driver}/unbind"
# Validate paths exist
if not os.path.exists(unbind_path):
QMessageBox.warning(self, "Error", f"Unbind path does not exist:\n{unbind_path}")
return
# Use tee to write to sysfs without shell interpolation
proc = subprocess.Popen(['tee', unbind_path], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
_, stderr = proc.communicate(device_name.encode())
if proc.returncode == 0:
log.info("Unbound device %s from driver %s", device_name, driver)
QMessageBox.information(self, "Success", "Driver unbound.")
else:
log.error("Unbind failed: %s", stderr.decode())
QMessageBox.warning(self, "Error", f"Unbind failed: {stderr.decode()}")
def action_reprobe(self):
sys_path = self.device_data.get('SYS_PATH')
uevent_path = f"{sys_path}/uevent"
if not os.path.exists(uevent_path):
QMessageBox.warning(self, "Error", f"uevent path does not exist:\n{uevent_path}")
return
proc = subprocess.Popen(['tee', uevent_path], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
_, stderr = proc.communicate(b"add")
if proc.returncode == 0:
log.info("Reprobe triggered for %s", sys_path)
QMessageBox.information(self, "Success", "Rescan triggered.")
else:
log.error("Reprobe failed: %s", stderr.decode())
QMessageBox.warning(self, "Error", f"Reprobe failed: {stderr.decode()}")
def action_unload_module(self, mod):
if not mod or not re.match(r'^[a-zA-Z0-9_-]+$', mod):
QMessageBox.warning(self, "Error", "Invalid module name.")
return
if QMessageBox.question(self, "Confirm", f"Unload {mod}?") == QMessageBox.Yes:
self.run_root_command(['modprobe', '-r', mod])
# --- Main Window ---
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.is_root = (os.geteuid() == 0)
self._enum_thread = None
title = "LinMan - Device Manager"
if self.is_root:
title += " (Root)"
# Signal to other instances that we are alive
self._lock_fd = self._create_handshake_lock()
self.setWindowTitle(title)
self.resize(600, 750)
self.setWindowIcon(QIcon.fromTheme("computer"))
self.context = pyudev.Context()
self.resolver = SystemResolver()
self.categories = {}
self.show_hidden = False
self.setup_ui()
self.setup_monitor()
QTimer.singleShot(100, self.refresh_devices)
# If we are User, watch for the Root handshake file
if not self.is_root:
self.setup_handshake_watcher()
def _create_handshake_lock(self):
"""Creates a lockfile with PID. Uses flock for atomicity; cleaned up on exit."""
try:
fd = open(HANDSHAKE_FILE, 'w')
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
fd.write(str(os.getpid()))
fd.flush()
atexit.register(self._cleanup_handshake, fd)
return fd
except (OSError, IOError) as e:
log.warning("Failed to create handshake lock: %s", e)
return None
@staticmethod
def _cleanup_handshake(fd):
try:
fcntl.flock(fd, fcntl.LOCK_UN)
fd.close()
if os.path.exists(HANDSHAKE_FILE):
os.unlink(HANDSHAKE_FILE)
except (OSError, IOError):
pass
def setup_handshake_watcher(self):
"""Monitors for the handshake file. If seen, close this window."""
self.handshake_timer = QTimer(self)
self.handshake_timer.timeout.connect(self.check_handshake)
self.handshake_timer.start(500) # Check every 0.5 seconds
def check_handshake(self):
if not os.path.exists(HANDSHAKE_FILE):
return
try:
mtime = os.path.getmtime(HANDSHAKE_FILE)
if time.time() - mtime > 10:
return
# Verify the PID in the file is actually running
with open(HANDSHAKE_FILE, 'r') as f:
pid_str = f.read().strip()
if pid_str:
pid = int(pid_str)
if pid != os.getpid():
# Check if the process exists via /proc (works regardless of user)
if os.path.exists(f"/proc/{pid}"):
self.close()
except (IOError, ValueError):
pass
def setup_ui(self):
central = QWidget()
self.setCentralWidget(central)
layout = QVBoxLayout(central)
layout.setContentsMargins(0, 0, 0, 0)
# --- Menu Bar ---
menubar = self.menuBar()
view_menu = menubar.addMenu("&View")
scan_menu_action = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), "&Scan for hardware changes", self)
scan_menu_action.setShortcut(QKeySequence("F5"))
scan_menu_action.triggered.connect(self.refresh_devices)
view_menu.addAction(scan_menu_action)
view_menu.addSeparator()
self.hidden_action = QAction("Show &hidden devices", self)
self.hidden_action.setCheckable(True)
self.hidden_action.setChecked(False)
self.hidden_action.toggled.connect(self.toggle_hidden_devices)
view_menu.addAction(self.hidden_action)
help_menu = menubar.addMenu("&Help")
about_action = QAction("&About LinMan", self)
about_action.triggered.connect(self.show_about)
help_menu.addAction(about_action)
# --- Toolbar ---
toolbar = QToolBar()
toolbar.setMovable(False)
self.addToolBar(toolbar)
scan_action = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), "Scan", self)
scan_action.triggered.connect(self.refresh_devices)
toolbar.addAction(scan_action)
if not self.is_root:
empty = QWidget()
empty.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
toolbar.addWidget(empty)
shield_icon = QIcon.fromTheme("security-high")
if shield_icon.isNull(): shield_icon = self.style().standardIcon(QStyle.SP_VistaShield)
self.root_btn = QAction(shield_icon, "Root Mode", self)
self.root_btn.triggered.connect(self.restart_as_root)
toolbar.addAction(self.root_btn)
toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
# --- Tree ---
self.tree = QTreeWidget()
self.tree.setHeaderHidden(True)
self.tree.setAnimated(True)
self.tree.itemDoubleClicked.connect(self.show_properties)
self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self.show_context_menu)
self.tree.setFont(QApplication.font()) # Use system default font
layout.addWidget(self.tree)
self.root_item = QTreeWidgetItem(self.tree)
self.root_item.setText(0, socket.gethostname())
self.root_item.setIcon(0, self.style().standardIcon(QStyle.SP_ComputerIcon))
self.root_item.setExpanded(True)
# --- Status Bar ---
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.status_bar.showMessage("Ready")
def restart_as_root(self):
msg = "Restart LinMan in Root Mode?\n\nCheck your taskbar for the password prompt."
if QMessageBox.question(self, "Root Mode", msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes:
self.root_btn.setEnabled(False) # Prevent double click
# 1. PERMISSIONS
try:
subprocess.call(['xhost', '+SI:localuser:root'])
except (OSError, FileNotFoundError) as e:
log.debug("xhost not available: %s", e)
script_path = os.path.abspath(sys.argv[0])
current_python_path = os.pathsep.join(sys.path)
# 2. Find escalation tool
escalation_cmd = self._find_escalation_tool()
if not escalation_cmd:
QMessageBox.critical(self, "Error", "No privilege escalation tool found.\nInstall pkexec, kdesu, or configure sudo.")
self.root_btn.setEnabled(True)
return
# 3. COMMAND with ENVIRONMENT FORWARDING
# Forward icon/theme vars so root mode looks identical
env_vars = {
'DISPLAY': os.environ.get("DISPLAY", ":0"),
'XAUTHORITY': os.environ.get("XAUTHORITY", ""),
'PYTHONPATH': current_python_path,
'XDG_DATA_DIRS': os.environ.get("XDG_DATA_DIRS", "/usr/share:/usr/local/share"),
'XDG_CURRENT_DESKTOP': os.environ.get("XDG_CURRENT_DESKTOP", ""),
'DESKTOP_SESSION': os.environ.get("DESKTOP_SESSION", ""),
'QT_QPA_PLATFORM': 'xcb',
'QT_QPA_PLATFORMTHEME': os.environ.get("QT_QPA_PLATFORMTHEME", ""),
'GTK_THEME': os.environ.get("GTK_THEME", ""),
}
# Also forward icon theme if explicitly set
for key in ('ICON_THEME', 'QT_ICON_THEME', 'GTK2_RC_FILES', 'GTK_RC_FILES',
'KDE_FULL_SESSION', 'KDE_SESSION_VERSION', 'GNOME_DESKTOP_SESSION_ID',
'DBUS_SESSION_BUS_ADDRESS', 'HOME'):
val = os.environ.get(key)
if val:
env_vars[key] = val
cmd = escalation_cmd + ['env'] + [f'{k}={v}' for k, v in env_vars.items() if v] + [
sys.executable,
script_path
]