forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandombg
executable file
·77 lines (66 loc) · 2.08 KB
/
randombg
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
#! /usr/bin/env python
# Pick a new random background
# usage: randombg [directory]
# Default directory is ~/Images/Backgrounds/$dpy_width
import sys, os, subprocess
import random
def recursive_read(rootdir):
file_list = []
for root, dirs, files in os.walk(rootdir):
for filename in files:
# Exclude files without extensions, like Tags.
if filename.startswith("Tags"):
continue
if '.' not in filename:
continue
file_list.append(os.path.join(rootdir, root, filename))
return file_list
def set_random_bg(bgdir, arg):
images = recursive_read(bgdir)
if not images:
print "No images in", bgdir
sys.exit(1)
img = random.choice(images)
print "Setting background to", img
subprocess.call(['hsetroot', arg, img])
# If the dir is specified explicitly, go ahead and do it.
if len(sys.argv) > 1:
set_random_bg(sys.argv[1], '-fill')
# Find the current resolution:
fp = os.popen("xdpyinfo")
while True:
line = fp.readline().strip()
if line[0:11] == 'dimensions:':
parts = line[12:].split()[0].split('x')
width = int(parts[0])
height = int(parts[1])
break
fp.close()
if not width or not height:
print "Couldn't find screen dimensions!"
sys.exit(1)
basedir = os.path.expanduser("~/Images/Backgrounds")
bgdir = os.path.join(basedir, '%dx%d' % (width, height))
# If the exact right directory exists, use it.
if os.path.exists(bgdir):
print bgdir, "exists: using it"
set_random_bg(bgdir, '-fill')
sys.exit(0)
# We don't have images at exactly the right resolution.
# Try to find the closest match:
print "Looking for the closest match"
mindiff = 99999
bgdir = None
for d in os.listdir(basedir):
try:
parts = d.split('x')
if len(parts) == 2:
w = int(parts[0])
h = int(parts[1])
diff = abs(w - width) + abs(h - height)
if diff < mindiff:
mindiff = diff
bgdir = os.path.join(basedir, d)
except:
continue
set_random_bg(bgdir, '-fill')