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 Broytman <phd@phd.pp.ru>"
15 __copyright__ = "Copyright (C) 2000-2010 PhiloSoft Design"
16 __license__ = "GNU GPL"
23 def error(error_str, error_code=1):
24 sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
28 from ConfigParser import SafeConfigParser
30 xsetbg_dir = os.path.dirname(os.path.abspath(__file__))
33 config = SafeConfigParser()
34 config.read("xsetbg.conf")
36 if config.has_option("images", "directory") or \
37 config.has_option("images", "directory0") or \
38 config.has_option("images", "directory1"):
40 if config.has_option("images", "directory"):
41 image_dirs.append(config.get("images", "directory"))
42 if config.has_option("images", "directory0"):
43 image_dirs.append(config.get("images", "directory0"))
44 if config.has_option("images", "directory1"):
45 image_dirs.append(config.get("images", "directory1"))
48 option = "directory%d" % i
49 if config.has_option("images", option):
50 image_dirs.append(config.get("images", option))
55 image_dirs = ["images"]
57 image_dirs = [os.path.join(xsetbg_dir,
58 os.path.expandvars(os.path.expanduser(dirname)))
59 for dirname in image_dirs
62 # minimum time in seconds between background image changes
63 if config.has_option("xsetbg", "min_pause"):
64 min_pause = config.getint("xsetbg", "min_pause")
68 borders = config.get("xsetbg", "borders").split(',')
69 if config.has_option("xsetbg", "borders"):
70 borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
72 borders = ["darkcyan", "steelblue", "midnightblue"]
74 # minimum time in seconds between occurences of the same image
75 if config.has_option("xsetbg", "min_delay"):
76 min_delay = config.getint("xsetbg", "min_delay")
78 min_delay = 3600*24 # 24 hours
81 if config.has_option("httpd", "host"):
82 host = config.get("httpd", "host")
86 if config.has_option("httpd", "port"):
87 port = config.getint("httpd", "port")
89 error("Config must specify a port to listen. Abort.")
94 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
95 # readable only by the user
96 global_db_name = "xsetbg.db"
100 timestamp_key = "timestamp"
101 filename_key = "filename"
102 old_filename_key = "old_filename"
106 import anydbm, shelve
107 from time import time
108 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
110 # Create the database if it is not exists yet.
113 global_db = shelve.open(global_db_name, flag='c')
114 except anydbm.error, msg:
115 if str(msg) == "db type could not be determined":
116 os.remove(global_db_name)
117 global_db = shelve.open(global_db_name, flag='c')
119 # Remove old filenames
120 old_time = time() - min_delay
122 to_delete = [timestamp_key]
123 for key in global_db.keys():
124 if key.startswith('/') and global_db[key] < old_time:
125 to_delete.append(key)
127 for key in to_delete:
133 global_db.close() # Close DB in the parent process
138 for image_dir in image_dirs:
139 # List images in all subdirectories
140 for dirpath, dirs, files in os.walk(image_dir):
141 images.extend([os.path.join(dirpath, file) for file in files])
144 error("No images found. Abort.")
148 func._wsgi_published = True
152 def ping(force=False):
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 # Reopen the global persistent dictionary
166 global_db = shelve.open(global_db_name, 'w')
168 timestamp = global_db.get(timestamp_key)
169 current_time = time()
171 if not force and timestamp is not None and \
172 current_time - timestamp < min_pause: # Too early to change background
176 global_db[timestamp_key] = current_time
178 # Select a random image and check if we've seen it recently;
179 # loop until we can find a new image (never seen before) or old enough.
180 for i in xrange(len(images)): # ensure the loop is not infinite
181 image_name = random.choice(images)
182 if global_db.has_key(image_name):
183 image_time = global_db[image_name]
184 if current_time - image_time > min_delay:
188 global_db[image_name] = current_time
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 program_options = ["xli", "-onroot", "-quiet"] + \
196 ["-center", "-border", random.choice(borders), "-zoom", "auto",
199 rc = subprocess.call(program_options)
201 error("cannot execute xli!")
204 # Unlock and close the lock file
205 flock(lock_file, LOCK_UN)
207 # Flush and close the global persistent dictionary
208 if global_db: global_db.close()
216 QuitWSGIServer._quit_flag = True
219 from wsgiref.handlers import SimpleHandler
220 from wsgiref import simple_server
221 simple_server.ServerHandler = SimpleHandler # Stop logging to stdout
222 from wsgiref.simple_server import WSGIServer, make_server
225 commands = dict([(name, g[name]) for name in g
226 if getattr(g[name], '_wsgi_published', False)])
229 class QuitWSGIServer(WSGIServer):
232 def serve_forever(self):
233 while not self._quit_flag:
234 self.handle_request()
236 def app(env, start_response):
237 command = env['PATH_INFO'][1:] # Remove the leading slash
238 if command not in commands:
239 status = '404 Not found'
240 response_headers = [('Content-type', 'text/plain')]
241 start_response(status, response_headers)
242 return ['The command was not found.\n']
248 response_headers = [('Content-type', 'text/plain')]
249 start_response(status, response_headers)
250 return ['Error occured!\n']
253 response_headers = [('Content-type', 'text/plain')]
254 start_response(status, response_headers)
258 httpd = make_server(host, port, app, server_class=QuitWSGIServer)
259 httpd.serve_forever()