-
-def published(func):
- func._wsgi_published = True
- return func
-
-@published
-def ping(force=False):
- # Use the program's file as the lock file:
- # lock it to prevent two processes run in parallel.
- lock_file = open("xsetbg.py", 'r')
- try:
- flock(lock_file, LOCK_EX|LOCK_NB)
- except IOError: # already locked
- lock_file.close()
- return
-
-
- global_db = None
- try:
- # Reopen the global persistent dictionary
- global_db = shelve.open(global_db_name, 'w')
-
- timestamp = global_db.get(timestamp_key)
- current_time = time()
-
- if not force and timestamp is not None and \
- current_time - timestamp < min_pause: # Too early to change background
- return
-
- # Save current time
- global_db[timestamp_key] = current_time
-
- # Select a random image and check if we've seen it recently;
- # loop until we can find a new image (never seen before) or old enough.
- for i in xrange(len(images)): # ensure the loop is not infinite
- image_name = random.choice(images)
- if global_db.has_key(image_name):
- image_time = global_db[image_name]
- if current_time - image_time > min_delay:
- break
- else:
- break
- global_db[image_name] = current_time
-
- # Save filename
- if global_db.has_key(filename_key):
- global_db[old_filename_key] = global_db[filename_key]
- global_db[filename_key] = image_name
-
- program_options = ["xli", "-onroot", "-quiet"] + \
- ["-center", "-border", random.choice(borders), "-zoom", "auto",
- image_name]
-
- rc = subprocess.call(program_options)
- if rc:
- error("cannot execute xli!")
-
- finally:
- # Unlock and close the lock file
- flock(lock_file, LOCK_UN)
- lock_file.close()
- # Flush and close the global persistent dictionary
- if global_db: global_db.close()
-
-@published
-def force():
- ping(force=True)
-
-@published
-def stop():
- QuitWSGIServer._quit_flag = True
-
-
-g = globals().copy()
-commands = dict([(name, g[name]) for name in g
- if getattr(g[name], '_wsgi_published', False)])
-del g
-
-class QuitWSGIServer(WSGIServer):
- _quit_flag = False
-
- def serve_forever(self):
- while not self._quit_flag:
- self.handle_request()
-
-def app(env, start_response):
- command = env['PATH_INFO'][1:] # Remove the leading slash
- if command not in commands:
- status = '404 Not found'
- response_headers = [('Content-type', 'text/plain')]
- start_response(status, response_headers)
- return ['The command was not found.\n']