-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaypaper-video-random
More file actions
executable file
·1198 lines (1072 loc) · 52.5 KB
/
Copy pathwaypaper-video-random
File metadata and controls
executable file
·1198 lines (1072 loc) · 52.5 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
"""Apply Wallpaper Engine wallpapers per niri output with compatibility guards."""
from __future__ import annotations
import argparse
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from datetime import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import random
import re
import shutil
import subprocess
import sys
import time
from typing import Any
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mkv", ".avi", ".mov"}
STATIC_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
TEXT_SCAN_EXTENSIONS = {".html", ".htm", ".js", ".mjs", ".json"}
DEFAULT_ROOTS = [
Path("~/.steam/root/steamapps/workshop/content/431960").expanduser(),
Path("~/.steam/steam/steamapps/common/wallpaper_engine/projects/defaultprojects").expanduser(),
]
WAYPAPER = Path("~/.local/bin/waypaper").expanduser()
CONFIG_DIR = Path("~/.config/waypaper").expanduser()
RULES_PATH = CONFIG_DIR / "video-smart-rules.json"
STATE_DIR = Path("~/.local/state/waypaper").expanduser()
LOCK_PATH = STATE_DIR / "waypaper-video-random.lock"
LAST_RUN_PATH = STATE_DIR / "waypaper-video-random-last.json"
PRIVATE_RESTORE_PATH = STATE_DIR / "waypaper-video-random-restore.private.json"
BENCHMARK_PATH = STATE_DIR / "waypaper-video-random-benchmark.json"
METADATA_CACHE_PATH = STATE_DIR / "waypaper-video-metadata-cache.private.json"
XDG_STATE_HOME = Path(os.environ.get("XDG_STATE_HOME", "~/.local/state")).expanduser()
OVERRIDE_PATH = Path(os.environ.get("LZT_WALLPAPER_OVERRIDE_PATH", str(XDG_STATE_HOME / "lzt" / "wallpaper-override.json"))).expanduser()
DEFAULT_SUSPICIOUS_TITLE_REGEX = [
r"\bacam\b",
r"\bcamrip\b",
r"\bhdcam\b",
r"\bhdts\b",
r"\btelesync\b",
r"\btelecine\b",
]
COMPATIBILITY_PATTERNS = {
"web-audio-reactive": re.compile(r"AudioContext|AnalyserNode|getByteFrequencyData|registerAudioListener|wallpaperRegisterAudioListener|audio[-_ ]?react", re.I),
"web-wallpaper-engine-api": re.compile(r"wallpaperPropertyListener|applyUserProperties|window\.wallpaper|registerMediaPlaybackListener", re.I),
"web-pointer-reactive": re.compile(r"mousemove|pointermove|touchmove|deviceorientation|parallax|cursor", re.I),
"web-webgl": re.compile(r"\bTHREE\b|three(?:\.min)?\.js|WebGLRenderer|webgl", re.I),
"scene-audio-reactive": re.compile(r"audio|sound|pulse|bass|frequency|spectrum", re.I),
}
METADATA_CACHE: dict[str, Any] = {}
METADATA_CACHE_DIRTY = False
METADATA_CACHE_SCHEMA = 3
@dataclass(frozen=True)
class OutputInfo:
name: str
x: int
y: int
width: int
height: int
transform: str
@property
def orientation(self) -> str:
if self.height > self.width * 1.12:
return "vertical"
if self.width > self.height * 1.12:
return "horizontal"
return "square"
@dataclass(frozen=True)
class Candidate:
project_dir: Path
wallpaper_path: Path
title: str
wallpaper_type: str
width: int | None
height: int | None
duration: float | None
tags: tuple[str, ...]
@property
def token(self) -> str:
return project_token(self.project_dir)
@property
def entry_ext(self) -> str:
return self.wallpaper_path.suffix.casefold() or "none"
@property
def orientation(self) -> str:
if self.width is None or self.height is None:
return "unknown"
if self.height > self.width * 1.12:
return "vertical"
if self.width > self.height * 1.12:
return "horizontal"
return "square"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Apply Wallpaper Engine wallpapers with per-output isolation.")
parser.add_argument("--root", action="append", type=Path, help="Wallpaper Engine library root to scan.")
parser.add_argument("--monitor", action="append", help="Output to update. Defaults to detected niri outputs.")
parser.add_argument("--mode", choices=("video", "smart", "all"), default="video", help="Candidate policy: video only, video+scene, or every supported type.")
parser.add_argument("--same", action="store_true", help="Use the same wallpaper on all outputs, still applied per output.")
parser.add_argument("--allow-all", action="store_true", help="Allow the global All target. Disabled by default for safety.")
parser.add_argument("--allow-duplicates", action="store_true", help="Allow the same project on more than one output in one random run.")
parser.add_argument("--include-web", action="store_true", help="Allow web wallpapers even though they often depend on unsupported runtime APIs.")
parser.add_argument("--allow-audio-reactive", action="store_true", help="Allow audio-reactive web/scene wallpapers.")
parser.add_argument("--exclude-project", action="append", default=[], help="Exclude a sanitized project token such as we:abc123.")
parser.add_argument("--exclude-title", action="append", default=[], help="Exclude titles matching this regex. Stored only locally when used in rules.")
parser.add_argument("--restore", action="store_true", help="Restore the last private per-output wallpaper state for connected outputs.")
parser.add_argument("--restore-or-random", action="store_true", help="Restore if possible, otherwise run a random cycle.")
parser.add_argument("--restore-only", action="store_true", help="During restore, skip connected outputs that do not have saved state.")
parser.add_argument("--list", action="store_true", help="List candidates with compatibility metadata and exit.")
parser.add_argument("--benchmark", action="store_true", help="Measure scan/filter/selection timing and write benchmark JSON.")
parser.add_argument("--dry-run", action="store_true", help="Print sanitized commands without applying wallpapers.")
parser.add_argument("--verbose", action="store_true", help="Print sanitized child output even when commands succeed.")
parser.add_argument("--max-retries", type=int, default=2, help="Retry failed random selections per output unless the output has a fixed single-item playlist.")
parser.add_argument("--max-fixed-playlist-attempts", type=int, default=3, help="Retry a fixed single-item playlist this many times before using a static fallback.")
parser.add_argument("--fallback-wallpaper", type=Path, help="Static image to apply with swww when a fixed playlist item fails.")
return parser.parse_args()
@contextmanager
def single_run_lock():
STATE_DIR.mkdir(parents=True, exist_ok=True)
with LOCK_PATH.open("w", encoding="utf-8") as lock_file:
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("event=skip reason=already_running", file=sys.stderr)
raise SystemExit(75)
yield
def project_token(project_dir: Path) -> str:
digest = hashlib.sha256(str(project_dir).encode("utf-8", errors="replace")).hexdigest()[:12]
return f"we:{digest}"
def sanitize_text(value: str) -> str:
home = str(Path.home())
text = value.replace(home, "~")
replacements = [
("~/.steam/root/steamapps/workshop/content/431960", "[workshop]"),
("~/.steam/steam/steamapps/common/wallpaper_engine", "[wallpaper-engine]"),
("~/.steam/root/steamapps/common/wallpaper_engine", "[wallpaper-engine]"),
("~/.cache/waypaper", "[waypaper-cache]"),
]
for old, new in replacements:
text = text.replace(old, new)
return text
def notify(summary: str, body: str) -> None:
try:
if shutil.which("dms"):
subprocess.Popen(["dms", "notify", summary, body, "--app", "Waypaper"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
elif shutil.which("notify-send"):
subprocess.Popen(["notify-send", summary, body], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
pass
def _read_cmdline(pid: int) -> list[str]:
try:
raw = Path(f"/proc/{pid}/cmdline").read_bytes()
except OSError:
return []
return [part.decode("utf-8", errors="replace") for part in raw.split(b"\0") if part]
def _has_arg_value(args: list[str], flag: str, value: str) -> bool:
for index, item in enumerate(args):
if item == flag and index + 1 < len(args) and args[index + 1] == value:
return True
if item.startswith(f"{flag}=") and item.split("=", 1)[1] == value:
return True
return False
def _renderer_backend_for_args(args: list[str], output_name: str) -> str | None:
if not args:
return None
executable = Path(args[0]).name
if executable == "linux-wallpaperengine" and _has_arg_value(args, "--screen-root", output_name):
return "linux-wallpaperengine"
if executable == "mpvpaper" and output_name in args:
return "mpvpaper"
return None
def find_renderer(output_name: str) -> tuple[str, int] | None:
"""Return the newest known external renderer process for one output."""
matches: list[tuple[int, str]] = []
proc_root = Path("/proc")
for proc_dir in proc_root.iterdir():
if not proc_dir.name.isdigit():
continue
pid = int(proc_dir.name)
args = _read_cmdline(pid)
backend = _renderer_backend_for_args(args, output_name)
if backend:
matches.append((pid, backend))
if not matches:
return None
pid, backend = max(matches, key=lambda item: item[0])
return backend, pid
def _load_override_payload() -> dict[str, Any]:
try:
payload = json.loads(OVERRIDE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {"version": 1, "overrides": {}}
if not isinstance(payload, dict):
return {"version": 1, "overrides": {}}
overrides = payload.get("overrides")
if not isinstance(overrides, dict):
payload["overrides"] = {}
return payload
def _live_override_entries(overrides: dict[str, Any]) -> dict[str, Any]:
live: dict[str, Any] = {}
for monitor, entry in overrides.items():
if not isinstance(entry, dict):
continue
try:
pid = int(entry.get("pid", 0))
except (TypeError, ValueError):
continue
if pid > 0 and Path(f"/proc/{pid}").exists():
live[str(monitor)] = entry
return live
def write_override_file(public_results: list[dict[str, Any]]) -> None:
"""Write per-output renderer liveness for DMS/QML health checks.
Behaviour per monitor:
- returncode == 0 AND renderer alive in /proc → live entry {backend, pid, since}
- returncode != 0 (launch failed / detected crash) → quarantine entry
{backend: "quarantine", pid: 0, quarantine_reason, quarantine_since}
so the QML self-heal Timer can detect it and trigger fallback.
- previously-live entry whose /proc/<pid> is gone → entry removed
(plugin will read stale-data, see no override, and not relaunch;
this is correct: if the renderer died between writes, the next
successful apply_wallpaper() refreshes the entry).
"""
if not public_results:
return
payload = _load_override_payload()
overrides = _live_override_entries(payload.get("overrides", {}))
now = int(time.time())
for row in public_results:
monitor = str(row.get("monitor", "")).strip()
if not monitor:
continue
try:
returncode = int(row.get("returncode", 1))
except (TypeError, ValueError):
returncode = 1
if returncode != 0:
# Quarantine: signal the plugin to attempt fallback for this monitor
overrides[monitor] = {
"backend": "quarantine",
"pid": 0,
"quarantine_since": now,
"quarantine_reason": str(row.get("quarantine_reason") or "launch_failed"),
"quarantine_code": returncode,
"last_project": row.get("project"),
}
print(f"event=renderer_quarantine monitor={monitor} code={returncode} reason={sanitize_text(str(row.get('quarantine_reason') or 'launch_failed'))}")
continue
renderer = find_renderer(monitor)
if renderer is None:
overrides.pop(monitor, None)
print(f"event=renderer_pid_missing monitor={monitor} backend=external")
continue
backend, pid = renderer
overrides[monitor] = {
"backend": backend,
"pid": pid,
"since": now,
"project": row.get("project"),
"type": row.get("type"),
}
payload = {
"version": 1,
"updated_at": datetime.now().isoformat(timespec="seconds"),
"overrides": overrides,
}
try:
OVERRIDE_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp_path = OVERRIDE_PATH.with_name(f"{OVERRIDE_PATH.name}.tmp")
tmp_path.write_text(json.dumps(payload, sort_keys=True, separators=(",", ":")), encoding="utf-8")
tmp_path.chmod(0o600)
tmp_path.replace(OVERRIDE_PATH)
print(f"event=override_write monitors={','.join(sorted(overrides)) or '(none)'} path={sanitize_text(str(OVERRIDE_PATH))}")
except OSError as exc:
print(f"event=override_write_failed error={exc.__class__.__name__}", file=sys.stderr)
def print_state_event(row: dict[str, Any]) -> None:
monitor = str(row.get("monitor", "")).strip()
if not monitor:
return
print(
"event=state"
f" monitor={monitor}"
f" project={row.get('project')}"
f" returncode={row.get('returncode')}"
f" type={row.get('type')}"
f" entry_ext={row.get('entry_ext')}"
)
def classify_waypaper_log_failure(log_text: str) -> str:
shared_lib = re.search(r"error while loading shared libraries: ([^:\s]+)", log_text)
if shared_lib:
return f"missing shared library {shared_lib.group(1)}"
checks = [
("Project type missing", "missing project type or unresolved preset dependency"),
("[json.exception.parse_error", "renderer JSON parse failure"),
("Invalid vector format", "renderer rejected a scene vector value"),
("Property must have a value", "renderer rejected a property without value"),
("ReferenceError: engine is not defined", "scene expects unsupported Wallpaper Engine runtime globals"),
("Text objects are not supported yet", "scene contains unsupported text objects"),
("Unexpected type for property", "project uses an unsupported property type"),
]
for needle, hint in checks:
if needle in log_text:
return hint
return "linux-wallpaperengine exited during Waypaper launch"
def detect_waypaper_launch_failure(child_output: str, output_name: str) -> tuple[int, str, Path] | None:
log_paths = [Path(match) for match in re.findall(r"linux-wallpaperengine log file:\s*(\S+)", child_output)]
log_paths.extend(Path(match) for match in re.findall(r"(/\S*/\.cache/waypaper/linux-wallpaperengine/\S+\.log)", child_output))
seen: set[Path] = set()
for log_path in reversed(log_paths):
if log_path in seen or output_name not in log_path.name or not log_path.exists():
continue
seen.add(log_path)
try:
log_text = log_path.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
if "suppressing launch-failed notification" in log_text:
return None
match = re.search(r"Process status after initial check: exited with code (-?\d+)", log_text)
if match is None:
continue
return int(match.group(1)), classify_waypaper_log_failure(log_text), log_path
return None
def read_project_json(project_dir: Path) -> dict[str, Any]:
try:
data = json.loads((project_dir / "project.json").read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return {}
return data if isinstance(data, dict) else {}
def metadata_title(project_dir: Path) -> str:
data = read_project_json(project_dir)
title = data.get("title") or data.get("name")
if isinstance(title, str) and title.strip():
return title.strip()
return project_dir.name
def wallpaper_type(project_dir: Path) -> str:
kind = read_project_json(project_dir).get("type")
return str(kind).strip().lower() if kind else "unknown"
def entry_path(project_dir: Path) -> Path:
entry_name = read_project_json(project_dir).get("file")
if isinstance(entry_name, str) and entry_name.strip():
candidate = project_dir / entry_name
if candidate.exists():
return candidate
return project_dir
def read_text(path: Path, max_bytes: int = 512_000) -> str:
try:
return path.read_text(encoding="utf-8", errors="ignore")[:max_bytes]
except OSError:
return ""
def compatibility_tags(project_dir: Path, kind: str) -> tuple[str, ...]:
tags: list[str] = []
if kind == "video":
tags.append("native-video")
elif kind == "web":
tags.append("web-runtime")
elif kind == "scene":
tags.append("scene-runtime")
text_parts: list[str] = []
for candidate in sorted(project_dir.rglob("*"))[:1600]:
if candidate.is_file() and candidate.suffix.casefold() in TEXT_SCAN_EXTENSIONS:
text_parts.append(read_text(candidate))
if len(text_parts) >= 32:
break
text = "\n".join(text_parts)
for tag, pattern in COMPATIBILITY_PATTERNS.items():
if pattern.search(text):
if tag.startswith("web-") and kind != "web":
continue
if tag.startswith("scene-") and kind != "scene":
continue
tags.append(tag)
return tuple(dict.fromkeys(tags))
def probe_video(path: Path) -> tuple[int | None, int | None, float | None]:
if path.suffix.casefold() not in VIDEO_EXTENSIONS or shutil.which("ffprobe") is None:
return None, None, None
global METADATA_CACHE_DIRTY
try:
stat = path.stat()
cache_key = str(path)
cached = METADATA_CACHE.get(cache_key)
if isinstance(cached, dict) and cached.get("schema") == METADATA_CACHE_SCHEMA and cached.get("mtime_ns") == stat.st_mtime_ns and cached.get("size") == stat.st_size:
return cached.get("width"), cached.get("height"), cached.get("duration")
except OSError:
return None, None, None
command = [
"ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height,duration:stream_tags=rotate:stream_side_data=rotation", "-of", "json", str(path),
]
try:
result = subprocess.run(command, text=True, capture_output=True, timeout=2, check=False)
data = json.loads(result.stdout or "{}")
stream = (data.get("streams") or [{}])[0]
width = int(stream["width"]) if stream.get("width") else None
height = int(stream["height"]) if stream.get("height") else None
duration = float(stream["duration"]) if stream.get("duration") else None
rotate = 0
tags = stream.get("tags") if isinstance(stream.get("tags"), dict) else {}
if tags.get("rotate"):
rotate = abs(int(float(tags["rotate"]))) % 180
for side_data in stream.get("side_data_list", []) if isinstance(stream.get("side_data_list"), list) else []:
if isinstance(side_data, dict) and side_data.get("rotation"):
rotate = abs(int(float(side_data["rotation"]))) % 180
if rotate == 90 and width and height:
width, height = height, width
METADATA_CACHE[cache_key] = {
"schema": METADATA_CACHE_SCHEMA,
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
"width": width,
"height": height,
"duration": duration,
}
METADATA_CACHE_DIRTY = True
return width, height, duration
except (OSError, subprocess.SubprocessError, json.JSONDecodeError, ValueError, IndexError):
return None, None, None
def load_metadata_cache() -> None:
global METADATA_CACHE
try:
data = json.loads(METADATA_CACHE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
METADATA_CACHE = {}
return
METADATA_CACHE = data if isinstance(data, dict) else {}
def write_metadata_cache() -> None:
if not METADATA_CACHE_DIRTY:
return
STATE_DIR.mkdir(parents=True, exist_ok=True)
METADATA_CACHE_PATH.write_text(json.dumps(METADATA_CACHE, indent=2, sort_keys=True), encoding="utf-8")
METADATA_CACHE_PATH.chmod(0o600)
def candidate_for_project(project_dir: Path) -> Candidate | None:
kind = wallpaper_type(project_dir)
entry = entry_path(project_dir)
if kind not in {"scene", "video", "web"} or not entry.is_file():
return None
width, height, duration = probe_video(entry)
return Candidate(
project_dir=project_dir,
wallpaper_path=entry,
title=metadata_title(project_dir),
wallpaper_type=kind,
width=width,
height=height,
duration=duration,
tags=compatibility_tags(project_dir, kind),
)
def collect_candidates(roots: list[Path]) -> list[Candidate]:
candidates: dict[Path, Candidate] = {}
for root in roots:
root = root.expanduser()
if not root.exists():
continue
for project_json in root.rglob("project.json"):
candidate = candidate_for_project(project_json.parent)
if candidate is not None:
candidates[candidate.project_dir] = candidate
return sorted(candidates.values(), key=lambda item: item.title.casefold())
def niri_outputs() -> list[OutputInfo]:
if not os.environ.get("NIRI_SOCKET") and shutil.which("niri"):
runtime_dir = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
sockets = list(runtime_dir.glob("niri.*sock"))
if sockets:
def socket_mtime(socket_path: Path) -> float:
try:
return socket_path.stat().st_mtime
except OSError:
return 0.0
os.environ["NIRI_SOCKET"] = str(max(sockets, key=socket_mtime))
try:
result = subprocess.run(["niri", "msg", "-j", "outputs"], check=True, capture_output=True, text=True)
outputs = json.loads(result.stdout)
except (subprocess.CalledProcessError, FileNotFoundError, json.JSONDecodeError):
return []
rows: list[OutputInfo] = []
if isinstance(outputs, dict):
iterator = outputs.items()
elif isinstance(outputs, list):
iterator = ((str(item.get("name") or ""), item) for item in outputs if isinstance(item, dict))
else:
iterator = []
for name, data in iterator:
if not name:
continue
logical = data.get("logical", {}) if isinstance(data, dict) else {}
rows.append(OutputInfo(
name=name,
x=int(logical.get("x", 0) or 0),
y=int(logical.get("y", 0) or 0),
width=int(logical.get("width", 0) or 0),
height=int(logical.get("height", 0) or 0),
transform=str(logical.get("transform", "Normal")),
))
return sorted(rows, key=lambda item: (item.x, item.y, item.name))
def default_rules(outputs: list[OutputInfo]) -> dict[str, Any]:
return {
"exclude_projects": [],
"exclude_title_regex": [],
"exclude_path_regex": [],
"exclude_tags": ["web-audio-reactive", "web-wallpaper-engine-api"],
"reject_suspicious_titles": True,
"suspicious_title_regex": list(DEFAULT_SUSPICIOUS_TITLE_REGEX),
"rotation_mode": "sync-all",
"cycle_interval_seconds": 1800,
"playlist": [],
"per_output": {output.name: {"prefer_orientation": "auto", "playlist": [], "exclude_projects": []} for output in outputs},
"notes": "Local file. Use sanitized project tokens from --list/--benchmark in exclude_projects or playlists.",
}
def load_rules(outputs: list[OutputInfo]) -> dict[str, Any]:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
if not RULES_PATH.exists():
rules = default_rules(outputs)
RULES_PATH.write_text(json.dumps(rules, indent=2, sort_keys=True), encoding="utf-8")
RULES_PATH.chmod(0o600)
return rules
try:
data = json.loads(RULES_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return default_rules(outputs)
if not isinstance(data, dict):
return default_rules(outputs)
changed = False
if not isinstance(data.get("playlist"), list):
data["playlist"] = []
changed = True
if not isinstance(data.get("exclude_path_regex"), list):
data["exclude_path_regex"] = []
changed = True
if not isinstance(data.get("suspicious_title_regex"), list):
data["suspicious_title_regex"] = list(DEFAULT_SUSPICIOUS_TITLE_REGEX)
changed = True
if not isinstance(data.get("reject_suspicious_titles"), bool):
data["reject_suspicious_titles"] = bool(data.get("reject_suspicious_titles", True))
changed = True
rotation_mode = str(data.get("rotation_mode", "sync-all")).strip().lower()
if rotation_mode not in {"sync-all", "round-robin"}:
data["rotation_mode"] = "sync-all"
changed = True
else:
data["rotation_mode"] = rotation_mode
try:
cycle_interval_seconds = int(data.get("cycle_interval_seconds", 1800))
if cycle_interval_seconds <= 0:
raise ValueError
except (TypeError, ValueError):
cycle_interval_seconds = 1800
changed = True
data["cycle_interval_seconds"] = cycle_interval_seconds
per_output = data.setdefault("per_output", {})
if isinstance(per_output, dict):
for output in outputs:
if output.name not in per_output:
per_output[output.name] = {"prefer_orientation": "auto", "playlist": [], "exclude_projects": []}
changed = True
if changed:
RULES_PATH.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
RULES_PATH.chmod(0o600)
return data
def compile_patterns(patterns: list[str], scope: str) -> list[re.Pattern[str]]:
compiled: list[re.Pattern[str]] = []
for pattern in patterns:
try:
compiled.append(re.compile(pattern, re.I))
except re.error:
print(f"event=invalid_regex scope={scope} pattern={sanitize_text(pattern)}", file=sys.stderr)
return compiled
def filtered_candidates(candidates: list[Candidate], output: OutputInfo | None, rules: dict[str, Any], args: argparse.Namespace) -> list[Candidate]:
exclude_projects = set(rules.get("exclude_projects", [])) | set(args.exclude_project or [])
exclude_tags = set(rules.get("exclude_tags", []))
title_patterns = compile_patterns(list(rules.get("exclude_title_regex", [])) + list(args.exclude_title or []), "exclude_title_regex")
path_patterns = compile_patterns(list(rules.get("exclude_path_regex", [])), "exclude_path_regex")
global_playlist = set(rules.get("playlist", []) if isinstance(rules.get("playlist"), list) else [])
suspicious_patterns = compile_patterns(
list(rules.get("suspicious_title_regex", [])) if rules.get("reject_suspicious_titles", True) else [],
"suspicious_title_regex",
)
if output is not None:
per_output = rules.get("per_output", {}).get(output.name, {}) if isinstance(rules.get("per_output"), dict) else {}
exclude_projects |= set(per_output.get("exclude_projects", []))
playlist = set(per_output.get("playlist", []))
else:
playlist = set()
allowed_types = {"video"} if args.mode == "video" else {"video", "scene"} if args.mode == "smart" else {"video", "scene", "web"}
if args.include_web:
allowed_types.add("web")
out: list[Candidate] = []
for candidate in candidates:
if global_playlist and candidate.token not in global_playlist:
continue
if playlist and candidate.token not in playlist:
continue
if candidate.wallpaper_type not in allowed_types:
continue
if candidate.wallpaper_type == "web" and not args.include_web and args.mode != "all":
continue
if candidate.token in exclude_projects:
continue
if any(pattern.search(candidate.title) for pattern in title_patterns):
continue
path_text = f"{candidate.project_dir}\n{candidate.wallpaper_path}"
if any(pattern.search(path_text) for pattern in path_patterns):
continue
if any(pattern.search(candidate.title) or pattern.search(path_text) for pattern in suspicious_patterns):
continue
if not args.allow_audio_reactive and any(tag.endswith("audio-reactive") for tag in candidate.tags):
continue
if exclude_tags.intersection(candidate.tags):
continue
out.append(candidate)
return out
def orientation_score(output: OutputInfo, candidate: Candidate, rules: dict[str, Any]) -> int:
per_output = rules.get("per_output", {}).get(output.name, {}) if isinstance(rules.get("per_output"), dict) else {}
preferred = str(per_output.get("prefer_orientation", "auto"))
target = output.orientation if preferred == "auto" else preferred
if candidate.orientation == target:
return 100
if candidate.orientation == "square":
return 45
if candidate.orientation == "unknown":
return 20
return -20
def choose_for_outputs(outputs: list[OutputInfo], candidates: list[Candidate], rules: dict[str, Any], args: argparse.Namespace) -> list[tuple[OutputInfo, Candidate]]:
if args.same:
shared_pool = filtered_candidates(candidates, None, rules, args)
if not shared_pool:
raise SystemExit("No candidates available for --same.")
selected = random.choice(shared_pool)
return [(output, selected) for output in outputs]
restore_rows = load_private_restore_rows()
used: set[str] = set()
selections: list[tuple[OutputInfo, Candidate]] = []
for output in outputs:
pool = filtered_candidates(candidates, output, rules, args)
if not args.allow_duplicates:
pool = [candidate for candidate in pool if candidate.token not in used] or pool
if not pool:
fallback_row = restore_rows.get(output.name)
fallback_candidate = restore_candidate(fallback_row) if isinstance(fallback_row, dict) else None
if fallback_candidate is not None:
print(f"event=keep_current monitor={output.name} project={fallback_candidate.token} reason=no_candidates")
used.add(fallback_candidate.token)
selections.append((output, fallback_candidate))
continue
raise SystemExit(f"No candidates available for output: {output.name}")
best_score = max(orientation_score(output, item, rules) for item in pool)
best_pool = [item for item in pool if orientation_score(output, item, rules) == best_score]
selected = random.choice(best_pool)
used.add(selected.token)
selections.append((output, selected))
return selections
def _is_mpvpaper_alive_for_output(output_name: str) -> bool:
"""Check if mpvpaper is actually running for this output."""
try:
result = subprocess.run(
["pgrep", "-f", f"mpvpaper.*{output_name}"],
capture_output=True, check=False,
)
return result.returncode == 0
except (subprocess.CalledProcessError, FileNotFoundError):
return False
def _get_mpvpaper_wallpaper_path(output_name: str) -> str | None:
"""Get the actual wallpaper path that mpvpaper is showing for this output."""
try:
result = subprocess.run(
["pgrep", "-a", "-f", f"mpvpaper.*{output_name}"],
capture_output=True, check=False, text=True,
)
if result.returncode != 0:
return None
# mpvpaper command line has the path as last argument
# Format: mpvpaper ... output_name /path/to/video.mp4
parts = result.stdout.strip().split()
if len(parts) >= 2:
return parts[-1]
return None
except (subprocess.CalledProcessError, FileNotFoundError):
return None
def fallback_image_for_candidate(candidate: Candidate, configured_fallback: Path | None) -> Path | None:
if configured_fallback is not None:
fallback_path = configured_fallback.expanduser()
if fallback_path.exists() and fallback_path.suffix.casefold() in STATIC_IMAGE_EXTENSIONS:
return fallback_path
if candidate.wallpaper_path.exists() and candidate.wallpaper_path.suffix.casefold() in STATIC_IMAGE_EXTENSIONS:
return candidate.wallpaper_path
for name in ("preview.jpg", "preview.jpeg", "preview.png", "preview.gif", "preview.webp"):
preview = candidate.project_dir / name
if preview.exists():
return preview
return None
def apply_static_fallback(candidate: Candidate, output_name: str, args: argparse.Namespace, verbose: bool) -> tuple[dict[str, Any], Candidate] | None:
fallback_path = fallback_image_for_candidate(candidate, args.fallback_wallpaper)
if fallback_path is None:
print(f"event=fallback_skip monitor={output_name} project={candidate.token} reason=no_static_image")
return None
fallback_candidate = Candidate(
project_dir=candidate.project_dir,
wallpaper_path=fallback_path,
title=candidate.title,
wallpaper_type="static",
width=None,
height=None,
duration=None,
tags=("static-fallback",),
)
print(f"event=fallback_static monitor={output_name} project={candidate.token} entry_ext={fallback_candidate.entry_ext}")
if args.dry_run:
result = public_result(output_name, fallback_candidate, 0)
print_state_event(result)
return result, fallback_candidate
if shutil.which("swww") is None:
print(f"event=fallback_failed monitor={output_name} project={candidate.token} reason=swww_missing")
return public_result(output_name, fallback_candidate, 127), fallback_candidate
command = ["swww", "img", "--outputs", output_name, "--transition-type", "none", str(fallback_path)]
result = subprocess.run(command, text=True, capture_output=True, check=False)
if result.returncode != 0 or verbose:
tail = sanitize_text((result.stdout or "") + (result.stderr or "")).strip()
if tail:
print(tail)
public = public_result(output_name, fallback_candidate, result.returncode)
if result.returncode == 0:
_update_dms_wallpaper(output_name, str(fallback_path))
print_state_event(public)
else:
print(f"event=fallback_failed monitor={output_name} project={candidate.token} code={result.returncode}")
return public, fallback_candidate
def apply_wallpaper(candidate: Candidate, output_name: str, dry_run: bool, verbose: bool) -> dict[str, Any]:
current_row = load_private_restore_rows().get(output_name, {})
current_token = str(current_row.get("project") or "").strip() if isinstance(current_row, dict) else ""
if current_token == candidate.token and int(current_row.get("returncode", 0)) == 0:
# Check if mpvpaper is actually running AND showing the correct wallpaper
if _is_mpvpaper_alive_for_output(output_name):
running_path = _get_mpvpaper_wallpaper_path(output_name)
if running_path and Path(running_path).resolve() == candidate.wallpaper_path.resolve():
print(f"event=skip monitor={output_name} project={candidate.token} reason=already_active")
result = public_result(output_name, candidate, 0)
print_state_event(result)
return result
print(f"event=resume monitor={output_name} project={candidate.token} reason=mpvpaper_wrong_wallpaper")
else:
print(f"event=resume monitor={output_name} project={candidate.token} reason=was_active_but_dead")
command = [
str(WAYPAPER), "--backend", "linux-wallpaperengine", "--fill", "fill",
"--monitor", output_name, "--wallpaper", str(candidate.wallpaper_path), "--no-post-command",
]
risky_tags = [tag for tag in candidate.tags if tag != "native-video"]
if risky_tags:
tag_text = ",".join(risky_tags)
print(f"event=compat_warning monitor={output_name} project={candidate.token} tags={tag_text}")
notify("Wallpaper compatibility", f"{output_name}: {candidate.token} {tag_text}")
print(f"event=apply monitor={output_name} project={candidate.token} type={candidate.wallpaper_type} orientation={candidate.orientation} entry_ext={candidate.entry_ext}")
if dry_run:
print(f"event=dry_run monitor={output_name} command='waypaper --backend linux-wallpaperengine --fill fill --monitor {output_name} --wallpaper {candidate.token}{candidate.entry_ext} --no-post-command'")
result = public_result(output_name, candidate, 0)
print_state_event(result)
return result
# Use setsid to run in own session + process group so systemd KillMode=mixed
# does not cascade SIGTERM to children when the service exits
setsid_cmd = ["setsid", "--fork", "--"] + command
result = subprocess.run(setsid_cmd, check=False, capture_output=True, text=True)
raw_child_output = (result.stdout or "") + (result.stderr or "")
effective_returncode = result.returncode
launch_failure = detect_waypaper_launch_failure(raw_child_output, output_name)
if launch_failure is not None:
effective_returncode, reason, log_path = launch_failure
print(f"event=waypaper_launch_failed monitor={output_name} project={candidate.token} code={effective_returncode} reason={reason} log={sanitize_text(str(log_path))}")
notify("Wallpaper launch failed", f"{output_name}: {candidate.token} {reason}")
child_output = sanitize_text(raw_child_output)
if effective_returncode != 0 or verbose:
tail = "\n".join(child_output.splitlines()[-40:])
if tail:
print(tail)
print(f"event=done monitor={output_name} project={candidate.token} returncode={effective_returncode}")
quarantine_reason = "waypaper_launch_failed:" + reason if launch_failure is not None else None
result = public_result(output_name, candidate, effective_returncode, quarantine_reason)
# Sync to DMS if successful
if effective_returncode == 0 and not dry_run:
_update_dms_wallpaper(output_name, str(candidate.wallpaper_path))
print_state_event(result)
return result
def _update_dms_wallpaper(output_name: str, wallpaper_path: str) -> None:
"""Update DMS session data via IPC."""
try:
subprocess.run(
["dms", "ipc", "wallpaper", "setFor", output_name, wallpaper_path],
capture_output=True, check=False, text=True, timeout=5,
)
except (subprocess.TimeoutExpired, FileNotFoundError):
pass # DMS not available or timeout
def public_result(output_name: str, candidate: Candidate, returncode: int, quarantine_reason: str | None = None) -> dict[str, Any]:
data: dict[str, Any] = {
"monitor": output_name,
"project": candidate.token,
"returncode": returncode,
"type": candidate.wallpaper_type,
"orientation": candidate.orientation,
"entry_ext": candidate.entry_ext,
"tags": list(candidate.tags),
}
if quarantine_reason:
data["quarantine_reason"] = quarantine_reason
return data
def private_result(output_name: str, candidate: Candidate, returncode: int) -> dict[str, Any]:
data = public_result(output_name, candidate, returncode)
data.update({
"project_dir": str(candidate.project_dir),
"wallpaper_path": str(candidate.wallpaper_path),
"width": candidate.width,
"height": candidate.height,
"duration": candidate.duration,
})
return data
def load_private_restore_rows() -> dict[str, dict[str, Any]]:
try:
payload = json.loads(PRIVATE_RESTORE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
rows = payload.get("results", []) if isinstance(payload, dict) else []
out: dict[str, dict[str, Any]] = {}
for row in rows:
if not isinstance(row, dict):
continue
monitor = str(row.get("monitor", "")).strip()
if monitor:
out[monitor] = row
return out
def write_states(public_results: list[dict[str, Any]], private_results: list[dict[str, Any]]) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().isoformat(timespec="seconds")
public_payload = {"created_at": timestamp, "results": public_results}
merged_private = load_private_restore_rows()
for row in private_results:
monitor = str(row.get("monitor", "")).strip()
if not monitor:
continue
if int(row.get("returncode", 1)) == 0:
merged_private[monitor] = row
private_payload = {
"created_at": timestamp,
"results": [merged_private[name] for name in sorted(merged_private)],
}
LAST_RUN_PATH.write_text(json.dumps(public_payload, indent=2, sort_keys=True), encoding="utf-8")
PRIVATE_RESTORE_PATH.write_text(json.dumps(private_payload, indent=2, sort_keys=True), encoding="utf-8")
LAST_RUN_PATH.chmod(0o600)
PRIVATE_RESTORE_PATH.chmod(0o600)
for row in public_results:
try:
if int(row.get("returncode", 1)) == 0:
print_state_event(row)
except (TypeError, ValueError):
continue
write_override_file(public_results)
def stop_static_wallpaper_daemons(dry_run: bool, rules: dict[str, Any]) -> None:
if rules.get("keep_static_underlay") is True:
print("event=keep_static_underlay action=skip_stop_static_daemons")
return
for name, command in (("swww", ["swww", "kill"]), ("awww", ["awww", "kill"])):
probe = subprocess.run(["pgrep", "-x", f"{name}-daemon"], text=True, capture_output=True, check=False)
if probe.returncode != 0:
continue
print(f"event=stop_static_daemon name={name}")
if not dry_run:
subprocess.run(command, text=True, capture_output=True, check=False)
def restore_candidate(row: dict[str, Any]) -> Candidate | None:
project_dir = Path(str(row.get("project_dir", ""))).expanduser()
wallpaper_path = Path(str(row.get("wallpaper_path", ""))).expanduser()
if not project_dir.exists() or not wallpaper_path.exists():
return None
candidate = candidate_for_project(project_dir)
if candidate is None:
# Scene.pkg or other non-extractable project — use preview image directly
if wallpaper_path.suffix.lower() in {".jpg", ".jpeg", ".png", ".gif"}:
width, height, duration = probe_video(wallpaper_path)
return Candidate(
project_dir=project_dir,
wallpaper_path=wallpaper_path,
title=metadata_title(project_dir),
wallpaper_type="scene",
width=width,
height=height,
duration=duration,
tags=("preview-fallback",),
)
return None
if candidate.wallpaper_path != wallpaper_path:
width, height, duration = probe_video(wallpaper_path)
return Candidate(project_dir, wallpaper_path, metadata_title(project_dir), wallpaper_type(project_dir), width, height, duration, compatibility_tags(project_dir, wallpaper_type(project_dir)))
return candidate
def restore(outputs: list[OutputInfo], candidates: list[Candidate], rules: dict[str, Any], args: argparse.Namespace) -> int:
if not PRIVATE_RESTORE_PATH.exists():