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 global_db.close() # Close DB in parent process
130 timestamp_key = "timestamp"
131 filename_key = "filename"
132 old_filename_key = "old_filename"
137 for image_dir in image_dirs:
138 # List images in all subdirectories
139 for dirpath, dirs, files in os.walk(image_dir):
140 images.extend([os.path.join(dirpath, file) for file in files])
143 error("No images found. Abort.")
147 from PIL import Image
154 if len(sys.argv) not in (1, 2):
158 if len(sys.argv) == 2:
159 if sys.argv[1] == "force":
164 # Use the program's file as the lock file:
165 # lock it to prevent two processes run in parallel.
166 lock_file = open("xsetbg.py", 'r')
168 flock(lock_file , LOCK_EX|LOCK_NB)
169 except IOError: # already locked
176 # Re-seed the RNG; this is neccessary because ReadyExecd forks
177 # and RNG in a child process got the same seed from the parent
181 # Reopen the global persistent dictionary
182 global_db = shelve.open(global_db_name, 'w')
184 timestamp = global_db.get(timestamp_key)
185 current_time = time()
187 if not force and timestamp is not None and \
188 current_time - timestamp < min_pause: # Too early to change background
192 global_db[timestamp_key] = current_time
194 # Select a random image and check if we've seen it recently;
195 # loop until we can find a new image (never seen before) or old enough.
196 for i in xrange(len(images)): # ensure the loop is not infinite
197 image_name = random.choice(images)
198 if global_db.has_key(image_name):
199 image_time = global_db[image_name]
200 if current_time - image_time > min_delay:
204 global_db[image_name] = current_time
206 border = random.choice(borders)
207 root, ext = os.path.splitext(image_name)
210 if global_db.has_key(filename_key):
211 global_db[old_filename_key] = global_db[filename_key]
212 global_db[filename_key] = image_name
214 placement_options = []
216 image = Image.open(image_name, 'r')
217 im_w, im_h = image.size
219 if (im_w > screen_width) or (im_h > screen_height):
220 zoom = min(screen_width*100//im_w, screen_height*100//im_h)
221 if zoom > 0: placement_options = ["-zoom", str(zoom)]
224 # Unlock and close the lock file
225 flock(lock_file , LOCK_UN)
227 # Flush and close the global persistent dictionary
228 if global_db: global_db.close()
231 if ext.lower() in (".bmp", ".png"):
232 # xsetbg does not recognize BMP files.
233 # PNG files have gamma settings, and xli can adapt it to the display gamma;
234 # xloadimage/xview/xsetbg display them with wrong gamma.
235 program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
236 ["-center", "-border", border, image_name]
237 os.execlp(*program_options)
238 error("cannot execute xli!")
240 # ...but xli failed to load many image types, use xsetbg for them
241 program_options = ["xsetbg", "xsetbg"] + placement_options + \
242 ["-center", "-border", border, image_name]
243 os.execlp(*program_options)
244 error("cannot execute xsetbg!")
247 if __name__ == "__main__":