-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
6744 lines (5674 loc) · 223 KB
/
Copy pathmain.py
File metadata and controls
6744 lines (5674 loc) · 223 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
import os
import re
import json
import time
import signal
import shutil
import subprocess
import base64
import zlib
from pathlib import Path
from urllib.parse import quote
try:
import decky_plugin
except Exception:
decky_plugin = None
VERSION = "0.3.alfa"
GAMESCOPE_SESSION = Path("/usr/lib/steamos/gamescope-session")
BACKUP_ORIGINAL = Path("/usr/lib/steamos/gamescope-session.egpubridge-original")
BACKUP_LAST = Path("/usr/lib/steamos/gamescope-session.egpubridge-last")
LEGACY_BACKUP = Path("/usr/lib/steamos/gamescope-session.bak-egpu")
# eGPUBridge 0.2.00 safe wrapper config.
# Do NOT patch /usr/lib/steamos/gamescope-session for normal display switching.
PLUGIN_DIR = Path("/home/deck/homebrew/plugins/eGPUBridge")
LOG_PATH = PLUGIN_DIR / "plugin.log"
STATUS_PATH = PLUGIN_DIR / "last_status.json"
OUTPUT_ORDER_CONF = PLUGIN_DIR / "output_order.conf"
PREFER_VK_DEVICE_CONF = PLUGIN_DIR / "prefer_vk_device.conf"
GAMESCOPE_MODE_CONF = PLUGIN_DIR / "gamescope_mode.conf"
ENV_OVERRIDE = Path("/home/deck/.config/environment.d/99-egpubridge.conf")
# Vendor branching infrastructure
VENDOR_FILE = Path("/home/deck/.config/egpubridge/vendor")
PROGRESS_FILE = PLUGIN_DIR / "operation_progress.json"
PCI_VENDOR_AMD = "0x1002"
PCI_VENDOR_NVIDIA = "0x10de"
PCI_VENDOR_INTEL = "0x8086"
_operation_lock = None
def _read_vendor() -> str:
try:
v = VENDOR_FILE.read_text().strip().lower()
if v in ("amd", "nvidia", "auto"):
return v
except Exception:
pass
return "auto"
def _write_vendor(vendor: str):
VENDOR_FILE.parent.mkdir(parents=True, exist_ok=True)
VENDOR_FILE.write_text(vendor.strip().lower() + "\n")
def _detect_vendor_from_pci() -> str:
for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
device = card / "device"
if not device.exists():
continue
boot_vga = ""
vendor = ""
try:
boot_vga = (device / "boot_vga").read_text(errors="ignore").strip()
vendor = (device / "vendor").read_text(errors="ignore").strip().lower()
except Exception:
continue
if boot_vga == "1":
continue
if vendor == PCI_VENDOR_NVIDIA:
return "nvidia"
if vendor == PCI_VENDOR_AMD:
return "amd"
return "amd"
def get_active_vendor() -> str:
v = _read_vendor()
if v == "auto":
return _detect_vendor_from_pci()
return v
def _query_nvidia_smi() -> dict:
result = {"available": False, "name": None, "temp_c": None, "mem_used_mb": None, "mem_total_mb": None, "power_w": None}
try:
r = run(["/usr/bin/nvidia-smi", "--query-gpu=name,temperature.gpu,memory.used,memory.total,power.default_limit", "--format=csv,noheader,nounits"], timeout=5)
if r.get("rc") != 0:
return result
parts = [x.strip() for x in r.get("out", "").split(",")]
if len(parts) >= 5:
result["available"] = True
result["name"] = parts[0]
result["temp_c"] = float(parts[1]) if parts[1] not in ("[N/A]", "") else None
result["mem_used_mb"] = float(parts[2]) if parts[2] not in ("[N/A]", "") else None
result["mem_total_mb"] = float(parts[3]) if parts[3] not in ("[N/A]", "") else None
result["power_w"] = float(parts[4]) if parts[4] not in ("[N/A]", "") else None
except Exception:
pass
return result
def _write_progress(stage: str, percent: int, message: str):
try:
data = {"stage": stage, "percent": percent, "message": message, "timestamp": int(time.time())}
PROGRESS_FILE.write_text(json.dumps(data) + "\n")
except Exception:
pass
def _read_progress() -> dict:
try:
return json.loads(PROGRESS_FILE.read_text())
except Exception:
return {"stage": "idle", "percent": 0, "message": ""}
def _begin_operation(name: str) -> bool:
global _operation_lock
if _operation_lock is not None:
return False
_operation_lock = name
return True
def _end_operation():
global _operation_lock
_operation_lock = None
DEFAULT_WIDTH = 1920
DEFAULT_HEIGHT = 1080
DEFAULT_REFRESH = 60
# Device hint database — labels only, never used for routing.
DEVICE_HINTS = {
("ASUSTeK COMPUTER INC.", "RC71L"): "ASUS ROG Ally",
("ASUSTeK COMPUTER INC.", "RC72LA"): "ASUS ROG Ally X",
("ASUSTeK COMPUTER INC.", "RC72L"): "ASUS ROG Ally X",
("LENOVO", "Legion Go 8APU1"): "Lenovo Legion Go",
("LENOVO", "Legion Go S 8APU1"): "Lenovo Legion Go S",
("LENOVO", "Legion Go S 8ARP1"): "Lenovo Legion Go S",
("Valve", "Jupiter"): "Steam Deck",
("Valve", "Galileo"): "Steam Deck OLED",
("Valve", "Valve Jupiter"): "Steam Deck",
("Valve", "Valve Galileo"): "Steam Deck OLED",
}
def detect_device_hint():
vendor = _read_text("/sys/devices/virtual/dmi/id/sys_vendor")
product = _read_text("/sys/devices/virtual/dmi/id/product_name")
if not vendor or not product:
return None
friendly = DEVICE_HINTS.get((vendor, product))
if not friendly:
for (v, p), label in DEVICE_HINTS.items():
if v == vendor and product.startswith(p.split()[0]):
friendly = label
break
return {
"vendor": vendor,
"product_name": product,
"friendly_name": friendly or (vendor + " " + product),
"known": friendly is not None,
"source": "dmi",
}
def detect_drm_driver(card_path=None):
"""Detect DRM driver name from sysfs. Falls back to 'unknown'."""
if card_path:
link = Path(card_path) / "device" / "driver"
if link.exists():
try:
return link.resolve().name
except Exception:
pass
# Fallback: scan all cards for first non-vgem driver
for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
link = card / "device" / "driver"
if link.exists():
try:
name = link.resolve().name
if name not in ("vgem", "ast"):
return name
except Exception:
pass
return "unknown"
def find_internal_display_card():
"""Find the card and eDP connector for the internal display.
Returns (card_name, connector_name, sysfs_path) or ("card0", "eDP-1", None) as fallback."""
for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
for conn in sorted(card.glob("*-eDP-*")):
status_file = conn / "status"
if status_file.exists():
try:
status = status_file.read_text(errors="ignore").strip()
if status == "connected":
card_name = card.name # "card0", "card2", etc.
conn_name = conn.name.split("-", 1)[1] if "-" in conn.name else "eDP-1"
return card_name, conn_name, str(conn)
except Exception:
pass
# Fallback: try any eDP connector
for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
for conn in card.glob("*-eDP-*"):
card_name = card.name
conn_name = conn.name.split("-", 1)[1] if "-" in conn.name else "eDP-1"
return card_name, conn_name, str(conn)
return "card0", "eDP-1", None
def rotate_log_if_needed():
try:
max_bytes = 2 * 1024 * 1024
keep_bytes = 700 * 1024
if LOG_PATH.exists() and LOG_PATH.stat().st_size > max_bytes:
data = LOG_PATH.read_bytes()
LOG_PATH.with_suffix(".log.1").write_bytes(data[-keep_bytes:])
LOG_PATH.write_text(
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] log rotated by eGPUBridge {VERSION}\\n",
encoding="utf-8",
)
except Exception:
pass
def log(msg: str):
try:
PLUGIN_DIR.mkdir(parents=True, exist_ok=True)
rotate_log_if_needed()
msg = str(msg)
if len(msg) > 3500:
msg = msg[:3500] + "... <truncated>"
with open(LOG_PATH, "a", encoding="utf-8") as f:
f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}\\n")
except Exception:
pass
def _compact_log_text(text: str, limit: int = 900) -> str:
"""
v0.7.11:
Keep plugin.log small.
Heavy commands like modetest/debugfs may return thousands of lines.
We keep only useful summary lines and hard-limit the final string.
"""
text = str(text or "")
if not text:
return ""
useful = []
keywords = (
"connected",
"disconnected",
"HDMI",
"DP-",
"eDP",
"mode:",
"3840x2160",
"2560x1440",
"1920x1080",
"1280x720",
"GT/s",
"Width",
"Speed",
"error",
"failed",
"unauthorized",
"offline",
"awake",
"asleep",
"state=",
"mWakefulness",
"Display Power",
)
for line in text.splitlines():
if any(k.lower() in line.lower() for k in keywords):
useful.append(line.strip())
if len(useful) >= 28:
break
compact = "\n".join(useful) if useful else text[:limit]
if len(compact) > limit:
compact = compact[:limit] + "...[truncated]"
return compact.replace("\x00", "")
def _is_quiet_status_cmd(cmd) -> bool:
"""
Avoid plugin.log spam from frequent background status polling.
These commands are still logged when they fail.
"""
try:
if cmd and str(cmd[0]) == "/usr/bin/ping":
return True
s = " ".join(map(str, cmd))
except Exception:
return False
quiet_parts = [
"/usr/bin/lspci -s",
"/usr/bin/pgrep -naf",
f"/usr/bin/modetest -M {detect_drm_driver()}",
"/usr/bin/cat /sys/kernel/debug/dri/",
]
return any(x in s for x in quiet_parts)
def run(cmd, timeout=12):
# EGPUBRIDGE_QUIET_PING_V0726
# TV network probe must never flood plugin.log when Wi-Fi/TV is unavailable.
try:
if cmd and str(cmd[0]) == "/usr/bin/ping":
cp = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return {
"ok": cp.returncode == 0,
"rc": cp.returncode,
"out": cp.stdout or "",
"err": cp.stderr or "",
"cmd": cmd,
}
except Exception as e:
return {
"ok": False,
"rc": -1,
"out": "",
"err": str(e),
"cmd": cmd,
}
quiet = _is_quiet_status_cmd(cmd)
if not quiet:
log("RUN: " + " ".join(map(str, cmd)))
try:
p = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=timeout,
)
out = (p.stdout or "").strip()
err = (p.stderr or "").strip()
if (not quiet) or p.returncode != 0:
try:
log(f"RC={p.returncode} OUT={_compact_log_text(out, 900)} ERR={_compact_log_text(err, 900)}")
except Exception:
log(f"RC={p.returncode} OUT={out[:900]} ERR={err[:900]}")
return {
"ok": p.returncode == 0,
"rc": p.returncode,
"out": out,
"err": err,
"cmd": cmd,
}
except Exception as e:
log(f"EXC running {cmd}: {e}")
return {
"ok": False,
"rc": -1,
"out": "",
"err": str(e),
"cmd": cmd,
}
class _TimeoutError(Exception):
pass
class plugin_timeout:
"""SIGALRM-based hard timeout context manager.
Kills truly stuck processes that ignore subprocess timeout.
Only works on the main thread — for executor threads use subprocess.run(timeout=N)."""
@staticmethod
def time_limit(seconds: int):
class _CM:
def __init__(self, s):
self.s = s
def __enter__(self):
def _handler(signum, frame):
raise _TimeoutError(f"Operation timed out after {self.s}s")
self.old = signal.signal(signal.SIGALRM, _handler)
signal.alarm(self.s)
return self
def __exit__(self, *args):
signal.alarm(0)
if self.old:
signal.signal(signal.SIGALRM, self.old)
return False
return _CM(seconds)
def _shell_quote(s: str) -> str:
"""Single-quote a string for safe shell embedding."""
return "'" + s.replace("'", "'\\''") + "'"
def _run(cmd: str, timeout: int = 30, sudo: bool = False):
"""Shell-string command runner returning (rc, stdout) tuple.
Unlike run() which takes a list, _run() takes a shell string
(may contain pipes, redirects, semicolons) and returns a simple
(returncode, stdout) tuple. Based on xg-mobile-linux pattern."""
try:
if sudo:
cmd = f"/usr/bin/sudo sh -c {_shell_quote(cmd)}"
log(f"_RUN: {cmd[:200]}")
p = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
)
out = (p.stdout or "").strip()
if p.returncode != 0:
err = (p.stderr or "").strip()
log(f"_RUN RC={p.returncode} OUT={out[:500]} ERR={err[:500]}")
return (p.returncode, out)
except subprocess.TimeoutExpired:
log(f"_RUN TIMEOUT after {timeout}s: {cmd[:200]}")
return (-1, f"timeout after {timeout}s")
except Exception as e:
log(f"_RUN EXC: {e} cmd={cmd[:200]}")
return (-1, str(e))
def _run_user(cmd: str, timeout: int = 10) -> tuple:
"""Shell-string command runner WITHOUT sudo. For status checks, queries."""
return _run(cmd, timeout=timeout, sudo=False)
def read_text(path: Path) -> str:
try:
return path.read_text(encoding="utf-8", errors="replace")
except Exception:
return ""
def write_text(path: Path, text: str):
path.write_text(text, encoding="utf-8")
def atomic_write(path: Path, text: str):
tmp = path.with_suffix(path.suffix + ".tmp-egpubridge")
write_text(tmp, text)
os.replace(tmp, path)
def safe_backup_original():
"""
Сохраняет оригинальный gamescope-session.
Если уже есть старый ручной backup bak-egpu, используем его как эталон.
"""
if BACKUP_ORIGINAL.exists():
return str(BACKUP_ORIGINAL)
if LEGACY_BACKUP.exists():
shutil.copy2(LEGACY_BACKUP, BACKUP_ORIGINAL)
log(f"backup original from legacy {LEGACY_BACKUP} -> {BACKUP_ORIGINAL}")
return str(BACKUP_ORIGINAL)
if GAMESCOPE_SESSION.exists():
shutil.copy2(GAMESCOPE_SESSION, BACKUP_ORIGINAL)
log(f"backup original from current {GAMESCOPE_SESSION} -> {BACKUP_ORIGINAL}")
return str(BACKUP_ORIGINAL)
raise FileNotFoundError(str(GAMESCOPE_SESSION))
def get_drm_card_info(card: str):
card_path = Path("/sys/class/drm") / card
dev_link = card_path / "device"
real = ""
pci = ""
vendor = ""
device = ""
boot_vga = ""
try:
real = os.path.realpath(dev_link)
matches = re.findall(r"([0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-9])", real)
pci = matches[-1] if matches else ""
except Exception:
pass
try:
vendor = read_text(dev_link / "vendor").strip()
except Exception:
pass
try:
device = read_text(dev_link / "device").strip()
except Exception:
pass
try:
boot_vga = read_text(dev_link / "boot_vga").strip()
except Exception:
pass
lspci = ""
if pci:
lspci = run(["/usr/bin/lspci", "-s", pci], timeout=4).get("out", "")
connectors = []
for p in sorted(Path("/sys/class/drm").glob(f"{card}-*")):
name = p.name.replace(f"{card}-", "", 1)
if name.startswith("Writeback"):
continue
status = read_text(p / "status").strip()
enabled = read_text(p / "enabled").strip()
modes = [x.strip() for x in read_text(p / "modes").splitlines() if x.strip()]
connectors.append({
"name": name,
"full_name": p.name,
"status": status,
"enabled": enabled,
"modes": modes,
})
return {
"card": card,
"path": f"/dev/dri/{card}",
"pci": pci,
"vendor": vendor,
"device": device,
"boot_vga": boot_vga,
"lspci": lspci,
"is_amd": vendor.lower() == "0x1002",
"is_internal": boot_vga == "1",
"is_egpu": boot_vga != "1",
"connectors": connectors,
}
def scan_cards():
cards = []
for p in sorted(Path("/sys/class/drm").glob("card[0-9]")):
if p.name.startswith("card"):
cards.append(get_drm_card_info(p.name))
return cards
def pick_egpu(cards):
external = [
c for c in cards
if c.get("is_egpu") and Path(c.get("path", "")).exists()
]
if not external:
return None
for c in external:
for conn in c.get("connectors", []):
if conn.get("status") == "connected":
return c
return external[0]
def pick_connector(card):
if not card:
return None
connected = [
c for c in card.get("connectors", [])
if c.get("status") == "connected"
]
if not connected:
return None
# HDMI сначала, потому что твой рабочий кейс именно HDMI-A-1.
for c in connected:
if c.get("name", "").startswith("HDMI"):
return c
return connected[0]
def current_gamescope_process():
# Берём самый новый gamescope, иначе status может показывать старый PID.
r = run(["/usr/bin/pgrep", "-naf", "^gamescope|gamescope --"], timeout=4)
return r.get("out", "")
def _is_valid_egpu_vk_id(value: str) -> bool:
"""Check if value is a valid PCI vendor:device ID (not 'disabled')."""
v = str(value or "").strip().lower()
return bool(v) and v not in ("disabled", "none", "") and bool(re.fullmatch(r"[0-9a-f]{4}:[0-9a-f]{4}", v))
def _has_egpu_vk_in_gamescope(gs_cmdline: str) -> bool:
"""Check if gamescope process has any --prefer-vk-device with a real ID."""
return bool(re.search(r"--prefer-vk-device\s+[0-9a-fA-F]{4}:[0-9a-fA-F]{4}", gs_cmdline or ""))
def get_current_patch_state():
"""
eGPUBridge 0.2.00:
Status comes from wrapper config and current Gamescope process.
Legacy system-file patch state is kept only as diagnostic information.
"""
gs = current_gamescope_process()
output_order = read_text(OUTPUT_ORDER_CONF).strip() if OUTPUT_ORDER_CONF.exists() else ""
prefer_vk = read_text(PREFER_VK_DEVICE_CONF).strip() if PREFER_VK_DEVICE_CONF.exists() else ""
legacy_txt = read_text(GAMESCOPE_SESSION)
return {
"method": "wrapper-config",
"output_order": output_order,
"prefer_vk_device": prefer_vk,
"has_prefer_vk_9070": (
_is_valid_egpu_vk_id(prefer_vk)
or _has_egpu_vk_in_gamescope(gs)
),
"has_prefer_vk_active": (
_is_valid_egpu_vk_id(prefer_vk)
or _has_egpu_vk_in_gamescope(gs)
),
"has_1080p60": "-W 1920 -H 1080 -r 60" in gs,
"prefer_output": [output_order] if output_order else re.findall(r"\s-O\s+([^\n]+)", gs),
"has_env_override_file": ENV_OVERRIDE.exists(),
"backup_original_exists": BACKUP_ORIGINAL.exists(),
"legacy_backup_exists": LEGACY_BACKUP.exists(),
"legacy_system_file_has_prefer_vk_9070": _has_egpu_vk_in_gamescope(legacy_txt),
}
def patch_gamescope_session(vendor_device: str, output_name: str, width: int, height: int, refresh: int):
safe_backup_original()
if not GAMESCOPE_SESSION.exists():
raise FileNotFoundError(str(GAMESCOPE_SESSION))
shutil.copy2(GAMESCOPE_SESSION, BACKUP_LAST)
txt = read_text(GAMESCOPE_SESSION)
# Убираем старые вставки eGPUBridge, чтобы патч был идемпотентный.
txt = re.sub(r"^\s*--prefer-vk-device\s+[0-9a-fA-F]{4}:[0-9a-fA-F]{4}\s*\\\n", "", txt, flags=re.M)
txt = re.sub(r"^\s*-W\s+\d+\s+-H\s+\d+\s+-r\s+\d+\s*\\\n", "", txt, flags=re.M)
# Добавляем prefer-vk-device после generate-drm-mode.
txt = re.sub(
r"(^\s*--generate-drm-mode\s+fixed\s*\\\n)",
r"\1 --prefer-vk-device " + vendor_device + r" \\" + "\n",
txt,
count=1,
flags=re.M,
)
# Добавляем фиксированный безопасный режим после socket/stats.
txt = re.sub(
r'(^\s*-e\s+-R\s+"\$socket"\s+-T\s+"\$stats"\s*\\\n)',
r"\1 -W " + str(width) + " -H " + str(height) + " -r " + str(refresh) + r" \\" + "\n",
txt,
count=1,
flags=re.M,
)
# Меняем output preference.
# ВАЖНО: replacement через lambda, иначе одинарный trailing backslash ломает re.sub:
# bad escape (end of pattern)
txt = re.sub(
r"^\s*-O\s+.*$",
lambda _m: f" -O {output_name} \\",
txt,
count=1,
flags=re.M,
)
if "--prefer-vk-device" not in txt:
raise RuntimeError("Не удалось вставить --prefer-vk-device")
if f"-O {output_name}" not in txt:
raise RuntimeError("Не удалось вставить -O output")
if f"-W {width} -H {height} -r {refresh}" not in txt:
raise RuntimeError("Не удалось вставить режим вывода")
atomic_write(GAMESCOPE_SESSION, txt)
os.chmod(GAMESCOPE_SESSION, 0o755)
# Старый env override больше не используем.
try:
if ENV_OVERRIDE.exists():
ENV_OVERRIDE.unlink()
except Exception as e:
log(f"failed to delete env override: {e}")
return {
"ok": True,
"patched": True,
"vendor_device": vendor_device,
"output": output_name,
"mode": f"{width}x{height}@{refresh}",
"backup_original": str(BACKUP_ORIGINAL),
"backup_last": str(BACKUP_LAST),
}
def restore_gamescope_session():
src = None
if BACKUP_ORIGINAL.exists():
src = BACKUP_ORIGINAL
elif LEGACY_BACKUP.exists():
src = LEGACY_BACKUP
if not src:
raise FileNotFoundError("Нет backup оригинального gamescope-session")
shutil.copy2(src, GAMESCOPE_SESSION)
os.chmod(GAMESCOPE_SESSION, 0o755)
try:
if ENV_OVERRIDE.exists():
ENV_OVERRIDE.unlink()
except Exception as e:
log(f"failed to delete env override during restore: {e}")
return {
"ok": True,
"restored_from": str(src),
}
def restart_sddm():
clean_env = os.environ.copy()
for k in ("LD_LIBRARY_PATH", "LD_PRELOAD", "PYTHONHOME", "PYTHONPATH"):
clean_env.pop(k, None)
log("RUN CLEAN: /usr/bin/systemctl restart sddm")
try:
p = subprocess.run(
["sudo", "-n", "/usr/bin/systemctl", "restart", "sddm"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=20,
env=clean_env,
)
out = (p.stdout or "").strip()
err = (p.stderr or "").strip()
log(f"RC={p.returncode} OUT={out[:3000]} ERR={err[:3000]}")
return {
"ok": p.returncode == 0,
"rc": p.returncode,
"out": out,
"err": err,
"cmd": ["sudo", "-n", "/usr/bin/systemctl", "restart", "sddm"],
}
except Exception as e:
log(f"EXC clean restart sddm: {e}")
return {
"ok": False,
"rc": -1,
"out": "",
"err": str(e),
"cmd": ["sudo", "-n", "/usr/bin/systemctl", "restart", "sddm"],
}
def _read_int(path: Path):
try:
return int(path.read_text().strip())
except Exception:
return None
def _read_label(path: Path, fallback: str) -> str:
try:
s = path.read_text(encoding="utf-8", errors="replace").strip()
return s or fallback
except Exception:
return fallback
def collect_card_sensors(card_name: str):
"""
Collect AMDGPU hwmon telemetry for /sys/class/drm/cardX.
Values depend on what amdgpu exposes for this GPU.
"""
result = {
"ok": False,
"hwmon_paths": [],
"temps": [],
"voltages": [],
"powers": [],
"fans": [],
}
if not card_name:
return result
base = Path("/sys/class/drm") / card_name / "device" / "hwmon"
if not base.exists():
result["error"] = f"{base} not found"
return result
hwmons = sorted(base.glob("hwmon*"))
if not hwmons:
result["error"] = "no hwmon dirs"
return result
for hw in hwmons:
result["hwmon_paths"].append(str(hw))
name = _read_label(hw / "name", hw.name)
# Temperatures: millidegrees Celsius.
for f in sorted(hw.glob("temp*_input")):
idx = f.name.replace("temp", "").replace("_input", "")
raw = _read_int(f)
if raw is None:
continue
label = _read_label(hw / f"temp{idx}_label", f"temp{idx}")
result["temps"].append({
"name": name,
"label": label,
"value_c": round(raw / 1000.0, 1),
"raw": raw,
})
# Voltages: usually millivolts.
for f in sorted(hw.glob("in*_input")):
idx = f.name.replace("in", "").replace("_input", "")
raw = _read_int(f)
if raw is None:
continue
label = _read_label(hw / f"in{idx}_label", f"in{idx}")
result["voltages"].append({
"name": name,
"label": label,
"value_v": round(raw / 1000.0, 3),
"raw": raw,
})
# Power: usually microwatts.
for suffix in ["average", "input"]:
for f in sorted(hw.glob(f"power*_{suffix}")):
idx = f.name.replace("power", "").replace(f"_{suffix}", "")
raw = _read_int(f)
if raw is None:
continue
label = _read_label(hw / f"power{idx}_label", f"power{idx}_{suffix}")
result["powers"].append({
"name": name,
"label": label,
"kind": suffix,
"value_w": round(raw / 1000000.0, 1),
"raw": raw,
})
# Fan RPM.
for f in sorted(hw.glob("fan*_input")):
idx = f.name.replace("fan", "").replace("_input", "")
raw = _read_int(f)
if raw is None:
continue
label = _read_label(hw / f"fan{idx}_label", f"fan{idx}")
result["fans"].append({
"name": name,
"label": label,
"rpm": raw,
})
result["ok"] = bool(
result["temps"] or result["voltages"] or result["powers"] or result["fans"]
)
return result
def _safe_write_text(path: str, value: str):
try:
Path(path).write_text(value)
return {"ok": True, "path": path, "value": value}
except Exception as e:
return {"ok": False, "path": path, "value": value, "error": str(e)}
def find_framebuffer():
"""Find primary framebuffer device. Returns sysfs path like '/sys/class/graphics/fb0'."""
for fb in sorted(Path("/sys/class/graphics").glob("fb*")):
return str(fb)
return "/sys/class/graphics/fb0"
def find_framebuffer_console():
"""Find vtconsole bound to framebuffer (fbcon). Returns sysfs path like '/sys/class/vtconsole/vtcon1'."""
for vt in sorted(Path("/sys/class/vtconsole").glob("vtcon*")):
name_file = vt / "name"
if name_file.exists():
try:
name = name_file.read_text(errors="ignore").strip().lower()
if "frame buffer" in name or "fbcon" in name or "drm" in name:
return str(vt)
except Exception:
pass
# Fallback: return second vtconsole (often fbcon on SteamOS)
consoles = sorted(Path("/sys/class/vtconsole").glob("vtcon*"))
if len(consoles) >= 2:
return str(consoles[1])
if consoles:
return str(consoles[0])
return "/sys/class/vtconsole/vtcon1"
def find_internal_edp_connector_id():
"""
Find connected internal eDP connector id.
On this device it was 108, but we detect it dynamically.
"""
card_name, _, _ = find_internal_display_card()
r = run(["/usr/bin/modetest", "-M", detect_drm_driver(), "-D", f"/dev/dri/{card_name}", "-c"], timeout=8)
out = r.get("out", "") or ""
for line in out.splitlines():
# Example:
# 108 107 connected eDP-1
m = re.match(r"^\s*(\d+)\s+\d+\s+connected\s+(eDP-\d+)\b", line)
if m:
return {
"ok": True,
"connector_id": m.group(1),
"connector_name": m.group(2),
"source": "modetest",
}
# Fallback from our confirmed device.
return {
"ok": False,
"connector_id": "108",
"connector_name": "eDP-1",
"source": "fallback",
"error": "connected eDP connector not found in modetest output",
}
BACKLIGHT_SAVE_PATH = PLUGIN_DIR / "backlight_saved.txt"
_BACKLIGHT_SAVED = None
_BACKLIGHT_PATH_CACHE = None
def _find_backlight_path():
"""Find the internal display backlight brightness file. Vendor-agnostic."""
amdgpu = Path("/sys/class/backlight/amdgpu_bl0/brightness")
if amdgpu.exists():
return amdgpu
for bl in sorted(Path("/sys/class/backlight").glob("*/brightness")):
return bl
return None
def get_backlight_path():
global _BACKLIGHT_PATH_CACHE
if _BACKLIGHT_PATH_CACHE is None or not _BACKLIGHT_PATH_CACHE.exists():
_BACKLIGHT_PATH_CACHE = _find_backlight_path()
return _BACKLIGHT_PATH_CACHE
def _save_backlight():
global _BACKLIGHT_SAVED
bl = get_backlight_path()
if not bl:
return
try:
val = bl.read_text().strip()
_BACKLIGHT_SAVED = int(val)
except Exception:
_BACKLIGHT_SAVED = None
log(f"BACKLIGHT save={_BACKLIGHT_SAVED} setting=0")
try:
bl.write_text("0")
except Exception as e:
log(f"BACKLIGHT write failed: {e}")
def _restore_backlight():
global _BACKLIGHT_SAVED
bl = get_backlight_path()
if not bl:
return
if _BACKLIGHT_SAVED is None: