1 #! /usr/local/bin/python -O
2 """Select a random image from $HOME/lib/xsetbg/images subdirectories
3 and set it as the desktop wallpaper (display it in the root window).
5 Author: Oleg BroytMann <phd@phd.pp.ru>
6 Copyright (C) 2000-2006 PhiloSoft Design
9 __version__ = "$Revision$"[11:-2]
10 __author__ = "Oleg BroytMann <phd@phd.pp.ru>"
11 __copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
12 __date__ = "$Date$"[7:-2]
13 __revision__ = "$Id$"[5:-2]
20 sys.stderr.write("%s version %s\n" % (sys.argv[0], __version__))
21 sys.stderr.write("Usage: %s [force]\n" % sys.argv[0])
24 def error(error_str, error_code=1):
25 sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
29 xwininfo = os.popen("xwininfo -root", 'r')
30 xwininfo_lines = xwininfo.read()
33 error("calling xwininfo", rc)
37 for line in xwininfo_lines.split('\n'):
39 if line.startswith("Width: "):
40 screen_width = int(line[len("Width: "):])
41 elif line.startswith("Height: "):
42 screen_height = int(line[len("Height: "):])
44 if not screen_width or not screen_height:
45 error("parsing xwininfo output")
48 from ConfigParser import SafeConfigParser
50 xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
53 config = SafeConfigParser()
54 config.read("xsetbg.conf")
56 if config.has_option("images", "directory") or \
57 config.has_option("images", "directory0") or \
58 config.has_option("images", "directory1"):
60 if config.has_option("images", "directory"):
61 image_dirs.append(config.get("images", "directory"))
62 if config.has_option("images", "directory0"):
63 image_dirs.append(config.get("images", "directory0"))
64 if config.has_option("images", "directory1"):
65 image_dirs.append(config.get("images", "directory1"))
68 option = "directory%d" % i
69 if config.has_option("images", option):
70 image_dirs.append(config.get("images", option))
75 image_dirs = ["images"]
77 image_dirs = [os.path.join(xsetbg_dir,
78 os.path.expandvars(os.path.expanduser(dirname)))
79 for dirname in image_dirs
82 # minimum time in seconds between background image changes
83 if config.has_option("xsetbg", "min_pause"):
84 min_pause = config.getint("xsetbg", "min_pause")
88 borders = config.get("xsetbg", "borders").split(',')
89 if config.has_option("xsetbg", "borders"):
90 borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
92 borders = ["darkcyan", "steelblue", "midnightblue"]
94 # minimum time in seconds between occurences of the same image
95 if config.has_option("xsetbg", "min_delay"):
96 min_delay = config.getint("xsetbg", "min_delay")
98 min_delay = 3600*24 # 24 hours
103 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
104 # readable only by the user
105 global_db_name = "xsetbg.db"
109 import anydbm, shelve
110 from time import time
111 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
113 # Import pickle and all anydbm/shelve internal machinery, so that
114 # when ReadyExec forks they will be ready.
115 # Also create the database if it is not exists yet.
118 global_db = shelve.open(global_db_name, flag='c')
119 except anydbm.error, msg:
120 if str(msg) == "db type could not be determined":
121 os.remove(global_db_name)
122 global_db = shelve.open(global_db_name, flag='c')
124 global_db.close() # Close DB in parent process
128 timestamp_key = "timestamp"
129 filename_key = "filename"
130 old_filename_key = "old_filename"
135 for image_dir in image_dirs:
136 # List images in all subdirectories
137 for dirpath, dirs, files in os.walk(image_dir):
138 images.extend([os.path.join(dirpath, file) for file in files])
141 error("No images found. Abort.")
145 from PIL import Image
152 if len(sys.argv) not in (1, 2):
156 if len(sys.argv) == 2:
157 if sys.argv[1] == "force":
162 # Use the program's file as the lock file:
163 # lock it to prevent two processes run in parallel.
164 lock_file = open("xsetbg.py", 'r')
166 flock(lock_file , LOCK_EX|LOCK_NB)
167 except IOError: # already locked
174 # Re-seed the RNG; this is neccessary because ReadyExecd forks
175 # and RNG in a child process got the same seed from the parent
179 # Reopen the global persistent dictionary
180 global_db = shelve.open(global_db_name, 'w')
182 timestamp = global_db.get(timestamp_key)
183 current_time = time()
185 if not force and timestamp is not None and \
186 current_time - timestamp < min_pause: # Too early to change background
190 global_db[timestamp_key] = current_time
192 # Select a random image and check if we've seen it recently;
193 # loop until we can find a new image (never seen before) or old enough.
194 for i in xrange(len(images)): # ensure the loop is not infinite
195 image_name = random.choice(images)
196 if global_db.has_key(image_name):
197 image_time = global_db[image_name]
198 if current_time - image_time > min_delay:
202 global_db[image_name] = current_time
204 border = random.choice(borders)
205 root, ext = os.path.splitext(image_name)
208 if global_db.has_key(filename_key):
209 global_db[old_filename_key] = global_db[filename_key]
210 global_db[filename_key] = image_name
212 placement_options = []
214 image = Image.open(image_name, 'r')
215 im_w, im_h = image.size
217 if (im_w > screen_width) or (im_h > screen_height):
218 zoom = min(screen_width*100//im_w, screen_height*100//im_h)
219 if zoom > 0: placement_options = ["-zoom", str(zoom)]
222 # Unlock and close the lock file
223 flock(lock_file , LOCK_UN)
225 # Flush and close the global persistent dictionary
226 if global_db: global_db.close()
229 if ext.lower() in (".bmp", ".png"):
230 # xsetbg does not recognize BMP files.
231 # PNG files have gamma settings, and xli can adapt it to the display gamma;
232 # xloadimage/xview/xsetbg display them with wrong gamma.
233 program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
234 ["-center", "-border", border, image_name]
235 os.execlp(*program_options)
236 error("cannot execute xli!")
238 # ...but xli failed to load many image types, use xsetbg for them
239 program_options = ["xsetbg", "xsetbg"] + placement_options + \
240 ["-center", "-border", border, image_name]
241 os.execlp(*program_options)
242 error("cannot execute xsetbg!")
245 if __name__ == "__main__":