1 #! /usr/local/bin/python -O
2 """Set a random background image (XWin)
4 Select a random image from a (list of) directory(s)
5 and set it as the desktop wallpaper (display it in the root window)
6 using xli or xsetbg programs.
10 __version__ = "$Revision$"[11:-2]
11 __revision__ = "$Id$"[5:-2]
12 __date__ = "$Date$"[7:-2]
14 __author__ = "Oleg BroytMann <phd@phd.pp.ru>"
15 __copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
16 __license__ = "GNU GPL"
23 sys.stderr.write("%s version %s\n" % (sys.argv[0], __version__))
24 sys.stderr.write("Usage: %s [force]\n" % sys.argv[0])
27 def error(error_str, error_code=1):
28 sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
32 xwininfo = os.popen("xwininfo -root", 'r')
33 xwininfo_lines = xwininfo.read()
36 error("calling xwininfo", rc)
40 for line in xwininfo_lines.split('\n'):
42 if line.startswith("Width: "):
43 screen_width = int(line[len("Width: "):])
44 elif line.startswith("Height: "):
45 screen_height = int(line[len("Height: "):])
47 if not screen_width or not screen_height:
48 error("parsing xwininfo output")
51 from ConfigParser import SafeConfigParser
53 xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
56 config = SafeConfigParser()
57 config.read("xsetbg.conf")
59 if config.has_option("images", "directory") or \
60 config.has_option("images", "directory0") or \
61 config.has_option("images", "directory1"):
63 if config.has_option("images", "directory"):
64 image_dirs.append(config.get("images", "directory"))
65 if config.has_option("images", "directory0"):
66 image_dirs.append(config.get("images", "directory0"))
67 if config.has_option("images", "directory1"):
68 image_dirs.append(config.get("images", "directory1"))
71 option = "directory%d" % i
72 if config.has_option("images", option):
73 image_dirs.append(config.get("images", option))
78 image_dirs = ["images"]
80 image_dirs = [os.path.join(xsetbg_dir,
81 os.path.expandvars(os.path.expanduser(dirname)))
82 for dirname in image_dirs
85 # minimum time in seconds between background image changes
86 if config.has_option("xsetbg", "min_pause"):
87 min_pause = config.getint("xsetbg", "min_pause")
91 borders = config.get("xsetbg", "borders").split(',')
92 if config.has_option("xsetbg", "borders"):
93 borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
95 borders = ["darkcyan", "steelblue", "midnightblue"]
97 # minimum time in seconds between occurences of the same image
98 if config.has_option("xsetbg", "min_delay"):
99 min_delay = config.getint("xsetbg", "min_delay")
101 min_delay = 3600*24 # 24 hours
106 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
107 # readable only by the user
108 global_db_name = "xsetbg.db"
112 timestamp_key = "timestamp"
113 filename_key = "filename"
114 old_filename_key = "old_filename"
118 import anydbm, shelve
119 from time import time
120 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
122 # Import pickle and all anydbm/shelve internal machinery, so that
123 # when ReadyExec forks they will be ready.
124 # Also create the database if it is not exists yet.
127 global_db = shelve.open(global_db_name, flag='c')
128 except anydbm.error, msg:
129 if str(msg) == "db type could not be determined":
130 os.remove(global_db_name)
131 global_db = shelve.open(global_db_name, flag='c')
133 # Remove old filenames
134 old_time = time() - min_delay
136 to_delete = [timestamp_key]
137 for key in global_db.keys():
138 if key.startswith('/') and global_db[key] < old_time:
139 to_delete.append(key)
141 for key in to_delete:
147 global_db.close() # Close DB in the parent process
152 for image_dir in image_dirs:
153 # List images in all subdirectories
154 for dirpath, dirs, files in os.walk(image_dir):
155 images.extend([os.path.join(dirpath, file) for file in files])
158 error("No images found. Abort.")
162 from PIL import Image
169 if len(sys.argv) not in (1, 2):
173 if len(sys.argv) == 2:
174 if sys.argv[1] == "force":
179 # Use the program's file as the lock file:
180 # lock it to prevent two processes run in parallel.
181 lock_file = open("xsetbg.py", 'r')
183 flock(lock_file , LOCK_EX|LOCK_NB)
184 except IOError: # already locked
191 # Re-seed the RNG; this is neccessary because ReadyExecd forks
192 # and RNG in a child process got the same seed from the parent
196 # Reopen the global persistent dictionary
197 global_db = shelve.open(global_db_name, 'w')
199 timestamp = global_db.get(timestamp_key)
200 current_time = time()
202 if not force and timestamp is not None and \
203 current_time - timestamp < min_pause: # Too early to change background
207 global_db[timestamp_key] = current_time
209 # Select a random image and check if we've seen it recently;
210 # loop until we can find a new image (never seen before) or old enough.
211 for i in xrange(len(images)): # ensure the loop is not infinite
212 image_name = random.choice(images)
213 if global_db.has_key(image_name):
214 image_time = global_db[image_name]
215 if current_time - image_time > min_delay:
219 global_db[image_name] = current_time
221 border = random.choice(borders)
222 root, ext = os.path.splitext(image_name)
225 if global_db.has_key(filename_key):
226 global_db[old_filename_key] = global_db[filename_key]
227 global_db[filename_key] = image_name
229 placement_options = []
231 image = Image.open(image_name, 'r')
232 im_w, im_h = image.size
234 if (im_w > screen_width) or (im_h > screen_height):
235 zoom = min(screen_width*100//im_w, screen_height*100//im_h)
236 if zoom > 0: placement_options = ["-zoom", str(zoom)]
239 # Unlock and close the lock file
240 flock(lock_file , LOCK_UN)
242 # Flush and close the global persistent dictionary
243 if global_db: global_db.close()
246 if ext.lower() in (".bmp", ".png"):
247 # xsetbg does not recognize BMP files.
248 # PNG files have gamma settings, and xli can adapt it to the display gamma;
249 # xloadimage/xview/xsetbg display them with wrong gamma.
250 program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
251 ["-center", "-border", border, image_name]
252 os.execlp(*program_options)
253 error("cannot execute xli!")
255 # ...but xli failed to load many image types, use xsetbg for them
256 program_options = ["xsetbg", "xsetbg"] + placement_options + \
257 ["-center", "-border", border, image_name]
258 os.execlp(*program_options)
259 error("cannot execute xsetbg!")
262 if __name__ == "__main__":