Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 78 lines (66 sloc) 2.1 KB
#! /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 %s" % bgdir)
sys.exit(1)
img = random.choice(images)
print("Setting background to %s" % 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("%s exists: using it" % bgdir)
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')