forked from ryan4yin/wallpapers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default_wall.py
103 lines (83 loc) · 2.67 KB
/
default_wall.py
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
#!/usr/bin/env python3
"""
This script will randomly select a wallpaper from the wallpapers directory.
It will skip the last wallpaper used, so that you don't get the same wallpaper.
It will also set the wallpaper using `feh` for X11, or `swaybg` for Wayland.
Maintainer: ryan4yin [[email protected]]
"""
import os
import time
import random
from pathlib import Path
import subprocess
WALLPAPERS_DIR = "~/.config/wallpapers"
LAST_WALLPAPER_FILE = "/tmp/my_last_wallpaper"
IMAGE_EXTENSIONS = (
".jpg",
".jpeg",
".png",
# ".gif",
# ".webp"
)
def get_random_wallpaper():
wallpapers_dir = Path(WALLPAPERS_DIR).expanduser()
last_wallpaper_file = Path(LAST_WALLPAPER_FILE)
if last_wallpaper_file.exists():
last_wallpaper = Path(last_wallpaper_file.read_text().strip())
print("Last wallpaper:", last_wallpaper)
else:
last_wallpaper = None
wallpapers = [
p for p in Path(wallpapers_dir).glob("*") if p.suffix in IMAGE_EXTENSIONS
]
print("Found wallpaper:")
for p in wallpapers:
if p == last_wallpaper:
print(" ", p, "(skipped)")
wallpapers.remove(p)
else:
print(" ", p)
if not wallpapers:
raise RuntimeError("No wallpapers found!")
w = random.choice(wallpapers)
print("Selected wallpaper:", w)
last_wallpaper_file.write_text(str(w))
return w
def set_wallpaper_x11(path):
subprocess.run(["feh", "--bg-fill", path])
def set_wallpaper_wayland(path):
# find all swaybg processes
swaybg_pids = subprocess.run(
["pgrep", "-f", "swaybg"], stdout=subprocess.PIPE
).stdout.decode("utf-8")
# run swaybg in the background, and make it running even after the parent process exits
subprocess.Popen(
["swaybg", "--output", "*", "--mode", "fill", "--image", path],
start_new_session=True,
)
time.sleep(1)
# kill all old swaybg processes
for pid in swaybg_pids.splitlines():
try:
os.kill(int(pid), 9)
except ProcessLookupError:
pass
def set_wallpaper(path):
# check if we are running under x11 or wayland
if (
"WAYLAND_DISPLAY" in os.environ
or os.environ.get("XDG_SESSION_TYPE") == "wayland"
):
set_wallpaper_wayland(path)
else:
set_wallpaper_x11(path)
def get_default_wallpaper():
default_wallpaper = Path(WALLPAPERS_DIR).expanduser() / "default_wallpaper"
if not default_wallpaper.exists():
raise ValueError("Default wallpaper not found!")
return default_wallpaper
def main():
default_wallpaper = get_default_wallpaper()
set_wallpaper(default_wallpaper)
if __name__ == "__main__":
main()