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
10 __author__ = "Oleg BroytMann <phd@phd.pp.ru>"
11 __copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
12 __revision__ = "$Id$"[5:-2]
13 __date__ = "$Date$"[7:-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"]
97 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
98 # readable only by the user
99 global_db_name = "xsetbg.db"
103 import anydbm, shelve
104 from time import time
105 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
107 # Import pickle and all anydbm/shelve internal machinery, so that
108 # when ReadyExec forks they will be ready.
109 # Also create the database if it is not exists yet.
112 global_db = shelve.open(global_db_name, flag='c')
113 except anydbm.error, msg:
114 if str(msg) == "db type could not be determined":
115 os.remove(global_db_name)
116 global_db = shelve.open(global_db_name, flag='c')
118 global_db.close() # Close DB in parent process
122 timestamp_key = "timestamp"
123 filename_key = "filename"
124 old_filename_key = "old_filename"
129 for image_dir in image_dirs:
130 # List images in all subdirectories
131 for dirpath, dirs, files in os.walk(image_dir):
132 images.extend([os.path.join(dirpath, file) for file in files])
135 error("No images found. Abort.")
139 from PIL import Image
146 if len(sys.argv) not in (1, 2):
150 if len(sys.argv) == 2:
151 if sys.argv[1] == "force":
156 # Use the program's file as the lock file:
157 # lock it to prevent two processes run in parallel.
158 lock_file = open("xsetbg.py", 'r')
160 flock(lock_file , LOCK_EX|LOCK_NB)
161 except IOError: # already locked
168 # Re-seed the RNG; this is neccessary because ReadyExecd forks
169 # and RNG in a child process got the same seed from the parent
173 # Reopen the global persistent dictionary
174 global_db = shelve.open(global_db_name, 'w')
176 timestamp = global_db.get(timestamp_key)
177 current_time = time()
179 if not force and timestamp is not None and \
180 current_time - timestamp < min_pause: # Too early to change background
184 global_db[timestamp_key] = current_time
186 border = random.choice(borders)
187 image_name = random.choice(images)
188 root, ext = os.path.splitext(image_name)
191 if global_db.has_key(filename_key):
192 global_db[old_filename_key] = global_db[filename_key]
193 global_db[filename_key] = image_name
195 placement_options = []
197 image = Image.open(image_name, 'r')
198 im_w, im_h = image.size
200 if (im_w > screen_width) or (im_h > screen_height):
201 zoom = min(screen_width*100//im_w, screen_height*100//im_h)
202 if zoom > 0: placement_options = ["-zoom", str(zoom)]
205 # Unlock and close the lock file
206 flock(lock_file , LOCK_UN)
208 # Flush and close the global persistent dictionary
209 if global_db: global_db.close()
212 if ext.lower() in (".bmp", ".png"):
213 # xsetbg does not recognize BMP files.
214 # PNG files have gamma settings, and xli can adapt it to the display gamma;
215 # xloadimage/xview/xsetbg display them with wrong gamma.
216 program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
217 ["-center", "-border", border, image_name]
218 os.execlp(*program_options)
219 error("cannot execute xli!")
221 # ...but xli failed to load many image types, use xsetbg for them
222 program_options = ["xsetbg", "xsetbg"] + placement_options + \
223 ["-center", "-border", border, image_name]
224 os.execlp(*program_options)
225 error("cannot execute xsetbg!")
228 if __name__ == "__main__":