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-2009 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 from ConfigParser import SafeConfigParser
34 xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
37 config = SafeConfigParser()
38 config.read("xsetbg.conf")
40 if config.has_option("images", "directory") or \
41 config.has_option("images", "directory0") or \
42 config.has_option("images", "directory1"):
44 if config.has_option("images", "directory"):
45 image_dirs.append(config.get("images", "directory"))
46 if config.has_option("images", "directory0"):
47 image_dirs.append(config.get("images", "directory0"))
48 if config.has_option("images", "directory1"):
49 image_dirs.append(config.get("images", "directory1"))
52 option = "directory%d" % i
53 if config.has_option("images", option):
54 image_dirs.append(config.get("images", option))
59 image_dirs = ["images"]
61 image_dirs = [os.path.join(xsetbg_dir,
62 os.path.expandvars(os.path.expanduser(dirname)))
63 for dirname in image_dirs
66 # minimum time in seconds between background image changes
67 if config.has_option("xsetbg", "min_pause"):
68 min_pause = config.getint("xsetbg", "min_pause")
72 borders = config.get("xsetbg", "borders").split(',')
73 if config.has_option("xsetbg", "borders"):
74 borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
76 borders = ["darkcyan", "steelblue", "midnightblue"]
78 # minimum time in seconds between occurences of the same image
79 if config.has_option("xsetbg", "min_delay"):
80 min_delay = config.getint("xsetbg", "min_delay")
82 min_delay = 3600*24 # 24 hours
87 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
88 # readable only by the user
89 global_db_name = "xsetbg.db"
93 timestamp_key = "timestamp"
94 filename_key = "filename"
95 old_filename_key = "old_filename"
100 from time import time
101 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
103 # Import pickle and all anydbm/shelve internal machinery, so that
104 # when ReadyExec forks they will be ready.
105 # Also create the database if it is not exists yet.
108 global_db = shelve.open(global_db_name, flag='c')
109 except anydbm.error, msg:
110 if str(msg) == "db type could not be determined":
111 os.remove(global_db_name)
112 global_db = shelve.open(global_db_name, flag='c')
114 # Remove old filenames
115 old_time = time() - min_delay
117 to_delete = [timestamp_key]
118 for key in global_db.keys():
119 if key.startswith('/') and global_db[key] < old_time:
120 to_delete.append(key)
122 for key in to_delete:
128 global_db.close() # Close DB in the parent process
133 for image_dir in image_dirs:
134 # List images in all subdirectories
135 for dirpath, dirs, files in os.walk(image_dir):
136 images.extend([os.path.join(dirpath, file) for file in files])
139 error("No images found. Abort.")
143 if len(sys.argv) not in (1, 2):
147 if len(sys.argv) == 2:
148 if sys.argv[1] == "force":
153 # Use the program's file as the lock file:
154 # lock it to prevent two processes run in parallel.
155 lock_file = open("xsetbg.py", 'r')
157 flock(lock_file , LOCK_EX|LOCK_NB)
158 except IOError: # already locked
165 # Re-seed the RNG; this is neccessary because ReadyExecd forks
166 # and RNG in a child process got the same seed from the parent
170 # Reopen the global persistent dictionary
171 global_db = shelve.open(global_db_name, 'w')
173 timestamp = global_db.get(timestamp_key)
174 current_time = time()
176 if not force and timestamp is not None and \
177 current_time - timestamp < min_pause: # Too early to change background
181 global_db[timestamp_key] = current_time
183 # Select a random image and check if we've seen it recently;
184 # loop until we can find a new image (never seen before) or old enough.
185 for i in xrange(len(images)): # ensure the loop is not infinite
186 image_name = random.choice(images)
187 if global_db.has_key(image_name):
188 image_time = global_db[image_name]
189 if current_time - image_time > min_delay:
193 global_db[image_name] = current_time
196 if global_db.has_key(filename_key):
197 global_db[old_filename_key] = global_db[filename_key]
198 global_db[filename_key] = image_name
201 # Unlock and close the lock file
202 flock(lock_file , LOCK_UN)
204 # Flush and close the global persistent dictionary
205 if global_db: global_db.close()
207 program_options = ["xli", "xli", "-onroot", "-quiet"] + \
208 ["-center", "-border", random.choice(borders), "-zoom", "auto",
211 os.execlp(*program_options)
212 error("cannot execute xli!")
215 if __name__ == "__main__":