1 #! /usr/local/bin/python -O
2 """Set a random background image (XWin)
4 Select a random image from $HOME/lib/xsetbg/images subdirectories
5 and set it as the desktop wallpaper (display it in the root window).
9 __version__ = "$Revision$"[11:-2]
10 __revision__ = "$Id$"[5:-2]
11 __date__ = "$Date$"[7:-2]
13 __author__ = "Oleg BroytMann <phd@phd.pp.ru>"
14 __copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
15 __license__ = "GNU GPL"
22 sys.stderr.write("%s version %s\n" % (sys.argv[0], __version__))
23 sys.stderr.write("Usage: %s [force]\n" % sys.argv[0])
26 def error(error_str, error_code=1):
27 sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
31 xwininfo = os.popen("xwininfo -root", 'r')
32 xwininfo_lines = xwininfo.read()
35 error("calling xwininfo", rc)
39 for line in xwininfo_lines.split('\n'):
41 if line.startswith("Width: "):
42 screen_width = int(line[len("Width: "):])
43 elif line.startswith("Height: "):
44 screen_height = int(line[len("Height: "):])
46 if not screen_width or not screen_height:
47 error("parsing xwininfo output")
50 from ConfigParser import SafeConfigParser
52 xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
55 config = SafeConfigParser()
56 config.read("xsetbg.conf")
58 if config.has_option("images", "directory") or \
59 config.has_option("images", "directory0") or \
60 config.has_option("images", "directory1"):
62 if config.has_option("images", "directory"):
63 image_dirs.append(config.get("images", "directory"))
64 if config.has_option("images", "directory0"):
65 image_dirs.append(config.get("images", "directory0"))
66 if config.has_option("images", "directory1"):
67 image_dirs.append(config.get("images", "directory1"))
70 option = "directory%d" % i
71 if config.has_option("images", option):
72 image_dirs.append(config.get("images", option))
77 image_dirs = ["images"]
79 image_dirs = [os.path.join(xsetbg_dir,
80 os.path.expandvars(os.path.expanduser(dirname)))
81 for dirname in image_dirs
84 # minimum time in seconds between background image changes
85 if config.has_option("xsetbg", "min_pause"):
86 min_pause = config.getint("xsetbg", "min_pause")
90 borders = config.get("xsetbg", "borders").split(',')
91 if config.has_option("xsetbg", "borders"):
92 borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
94 borders = ["darkcyan", "steelblue", "midnightblue"]
96 # minimum time in seconds between occurences of the same image
97 if config.has_option("xsetbg", "min_delay"):
98 min_delay = config.getint("xsetbg", "min_delay")
100 min_delay = 3600*24 # 24 hours
105 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
106 # readable only by the user
107 global_db_name = "xsetbg.db"
111 import anydbm, shelve
112 from time import time
113 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
115 # Import pickle and all anydbm/shelve internal machinery, so that
116 # when ReadyExec forks they will be ready.
117 # Also create the database if it is not exists yet.
120 global_db = shelve.open(global_db_name, flag='c')
121 except anydbm.error, msg:
122 if str(msg) == "db type could not be determined":
123 os.remove(global_db_name)
124 global_db = shelve.open(global_db_name, flag='c')
126 # Remove old filenames
127 old_time = time() - min_delay
130 for key in global_db.keys():
131 if key.startswith('/') and global_db[key] < old_time:
132 to_delete.append(key)
134 for key in to_delete:
137 global_db.close() # Close DB in the parent process
141 timestamp_key = "timestamp"
142 filename_key = "filename"
143 old_filename_key = "old_filename"
148 for image_dir in image_dirs:
149 # List images in all subdirectories
150 for dirpath, dirs, files in os.walk(image_dir):
151 images.extend([os.path.join(dirpath, file) for file in files])
154 error("No images found. Abort.")
158 from PIL import Image
165 if len(sys.argv) not in (1, 2):
169 if len(sys.argv) == 2:
170 if sys.argv[1] == "force":
175 # Use the program's file as the lock file:
176 # lock it to prevent two processes run in parallel.
177 lock_file = open("xsetbg.py", 'r')
179 flock(lock_file , LOCK_EX|LOCK_NB)
180 except IOError: # already locked
187 # Re-seed the RNG; this is neccessary because ReadyExecd forks
188 # and RNG in a child process got the same seed from the parent
192 # Reopen the global persistent dictionary
193 global_db = shelve.open(global_db_name, 'w')
195 timestamp = global_db.get(timestamp_key)
196 current_time = time()
198 if not force and timestamp is not None and \
199 current_time - timestamp < min_pause: # Too early to change background
203 global_db[timestamp_key] = current_time
205 # Select a random image and check if we've seen it recently;
206 # loop until we can find a new image (never seen before) or old enough.
207 for i in xrange(len(images)): # ensure the loop is not infinite
208 image_name = random.choice(images)
209 if global_db.has_key(image_name):
210 image_time = global_db[image_name]
211 if current_time - image_time > min_delay:
215 global_db[image_name] = current_time
217 border = random.choice(borders)
218 root, ext = os.path.splitext(image_name)
221 if global_db.has_key(filename_key):
222 global_db[old_filename_key] = global_db[filename_key]
223 global_db[filename_key] = image_name
225 placement_options = []
227 image = Image.open(image_name, 'r')
228 im_w, im_h = image.size
230 if (im_w > screen_width) or (im_h > screen_height):
231 zoom = min(screen_width*100//im_w, screen_height*100//im_h)
232 if zoom > 0: placement_options = ["-zoom", str(zoom)]
235 # Unlock and close the lock file
236 flock(lock_file , LOCK_UN)
238 # Flush and close the global persistent dictionary
239 if global_db: global_db.close()
242 if ext.lower() in (".bmp", ".png"):
243 # xsetbg does not recognize BMP files.
244 # PNG files have gamma settings, and xli can adapt it to the display gamma;
245 # xloadimage/xview/xsetbg display them with wrong gamma.
246 program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
247 ["-center", "-border", border, image_name]
248 os.execlp(*program_options)
249 error("cannot execute xli!")
251 # ...but xli failed to load many image types, use xsetbg for them
252 program_options = ["xsetbg", "xsetbg"] + placement_options + \
253 ["-center", "-border", border, image_name]
254 os.execlp(*program_options)
255 error("cannot execute xsetbg!")
258 if __name__ == "__main__":