summaryrefslogtreecommitdiff
path: root/.config/sway/bin/wallpaper.py
blob: 1dad0450e6fb4b1740d5e720234b29f414ae3bc9 (plain)
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
#!/usr/bin/env python


import sys, os
import argparse, json
import random, re, subprocess, time


"""
" CLI
"""

parser = argparse.ArgumentParser(
    prog='wallpaper',
    description='Cycle through wallpapers'
)

parser.add_argument(
    '--config',
    required=True,
    help='{"<weight>": { "find": "<path>", "exclude": "<regex>" }, "<weight>":...}'
)

parser.add_argument(
    '--interval',
    default=600
)

args = parser.parse_args()

config = json.loads(args.config)


"""
" Program
"""

running_bg_process = None
while True:
    probability_number = random.randrange(start=1, stop=100, step=1)

    # select config to use based on args.config
    # see https://stackoverflow.com/questions/16489449/select-element-from-array-with-probability-proportional-to-its-value/16490300#16490300
    selected_config = {}
    accumulative = 0
    for weight, wallpaper_path in config.items():
        lower_bound = accumulative
        accumulative += int(weight)
        upper_bound = accumulative

        if lower_bound <= probability_number and probability_number <= upper_bound:
            selected_config = wallpaper_path
            break

    # build list of file paths to choose from
    found_file_paths = []
    for dirpath, dirnames, filenames in os.walk(os.path.expandvars(wallpaper_path['find'])):
        for filename in filenames:
            found_file_paths.append(f'{dirpath}/{filename}')

    if 'exclude' in selected_config.keys():
        found_file_paths = list(filter(
            lambda file_path: (not re.match(os.path.expandvars(wallpaper_path['exclude']), file_path)),
            found_file_paths
        ))

    # run swaybg
    swaybg_cmd = ['swaybg', '-i', random.choice(found_file_paths), '-m', 'fill']
    replacing_process = subprocess.Popen(swaybg_cmd)

    # wait until new instance of swaybg has booted up properly
    time.sleep(5)

    # kill the previous process
    # the new swaybg process takes its place automatically
    if running_bg_process:
        running_bg_process.terminate()

    # set running process for next iteration
    running_bg_process = replacing_process

    # wait $INTERVAL seconds
    time.sleep(int(args.interval))