]> git.phdru.name Git - xsetbg.git/blobdiff - xsetbg.py
DBus.
[xsetbg.git] / xsetbg.py
index 3b3b02f045c109a13c69141bcffb625ece9cff14..0d9d646e50fd94963c435bb6832395c7dab78184 100755 (executable)
--- a/xsetbg.py
+++ b/xsetbg.py
@@ -1,53 +1,43 @@
-#! /usr/local/bin/python -O
-"""Select a random image from $HOME/lib/xsetbg/images subdirectories
-and set it as the desktop wallpaper (display it in the root window).
+#! /usr/bin/env python
+"""Set a random background image (XWin)
+
+Select a random image from a (list of) directory(s)
+and set it as the desktop wallpaper (display it in the root window)
+using xli program.
 
-Author: Oleg BroytMann <phd@phd.pp.ru>
-Copyright (C) 2000-2006 PhiloSoft Design
 """
 
 __version__ = "$Revision$"[11:-2]
-__author__ = "Oleg BroytMann <phd@phd.pp.ru>"
-__copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
-__date__ = "$Date$"[7:-2]
 __revision__ = "$Id$"[5:-2]
+__date__ = "$Date$"[7:-2]
+
+__author__ = "Oleg Broytman <phd@phdru.name>"
+__copyright__ = "Copyright (C) 2000-2010 PhiloSoft Design"
+__license__ = "GNU GPL"
 
 
 import sys, os
+from ConfigParser import SafeConfigParser
 
+import anydbm
+import random
+import shelve
+import subprocess
+from time import time
+from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
+
+from wsgiref import simple_server
+from wsgiref.handlers import SimpleHandler
+from wsgiref.simple_server import WSGIServer, make_server
+simple_server.ServerHandler = SimpleHandler # Stop logging to stdout
 
-def usage():
-   sys.stderr.write("%s version %s\n" % (sys.argv[0], __version__))
-   sys.stderr.write("Usage: %s [force]\n" % sys.argv[0])
-   sys.exit(0)
 
 def error(error_str, error_code=1):
    sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
    sys.exit(error_code)
 
 
-xwininfo = os.popen("xwininfo -root", 'r')
-xwininfo_lines = xwininfo.read()
-rc = xwininfo.close()
-if rc:
-   error("calling xwininfo", rc)
-
-screen_width = None
-screen_height = None
-for line in xwininfo_lines.split('\n'):
-   line = line.strip()
-   if line.startswith("Width: "):
-      screen_width = int(line[len("Width: "):])
-   elif line.startswith("Height: "):
-      screen_height = int(line[len("Height: "):])
-
-if not screen_width or not screen_height:
-   error("parsing xwininfo output")
-
-
-from ConfigParser import SafeConfigParser
-
-xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
+xsetbg_dir = os.path.dirname(os.path.abspath(__file__))
 os.chdir(xsetbg_dir)
 
 config = SafeConfigParser()
@@ -97,6 +87,17 @@ if config.has_option("xsetbg", "min_delay"):
 else:
    min_delay = 3600*24 # 24 hours
 
+# httpd settings
+if config.has_option("httpd", "host"):
+   host = config.get("httpd", "host")
+else:
+   host = 'localhost'
+
+if config.has_option("httpd", "port"):
+   port = config.getint("httpd", "port")
+else:
+   error("Config must specify a port to listen. Abort.")
+
 del config
 
 
@@ -105,14 +106,13 @@ os.umask(0066) # octal; -rw-------; make the global persistent dictionary
 global_db_name = "xsetbg.db"
 
 
-import random
-import anydbm, shelve
-from time import time
-from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
+# DB keys
+timestamp_key = "timestamp"
+filename_key = "filename"
+old_filename_key = "old_filename"
+
 
-# Import pickle and all anydbm/shelve internal machinery, so that
-# when ReadyExec forks they will be ready.
-# Also create the database if it is not exists yet.
+# Create the database if it is not exists yet.
 
 try:
    global_db = shelve.open(global_db_name, flag='c')
@@ -121,13 +121,21 @@ except anydbm.error, msg:
       os.remove(global_db_name)
       global_db = shelve.open(global_db_name, flag='c')
 
-global_db.close() # Close DB in parent process
+# Remove old filenames
+old_time = time() - min_delay
 
+to_delete = [timestamp_key]
+for key in global_db.keys():
+   if key.startswith('/') and global_db[key] < old_time:
+      to_delete.append(key)
 
-# DB keys
-timestamp_key = "timestamp"
-filename_key = "filename"
-old_filename_key = "old_filename"
+for key in to_delete:
+   try:
+      del global_db[key]
+   except KeyError:
+      pass
+
+global_db.close() # Close DB in the parent process
 
 
 images = []
@@ -141,29 +149,17 @@ if not images:
    error("No images found. Abort.")
 
 
-try:
-   from PIL import Image
-   use_PIL = True
-except ImportError:
-   use_PIL = False
-
-
-def run():
-   if len(sys.argv) not in (1, 2):
-      usage()
-
-   force = False
-   if len(sys.argv) == 2:
-      if sys.argv[1] == "force":
-         force = True
-      else:
-         usage()
+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)
+      flock(lock_file, LOCK_EX|LOCK_NB)
    except IOError: # already locked
       lock_file.close()
       return
@@ -171,11 +167,6 @@ def run():
 
    global_db = None
    try:
-      # Re-seed the RNG; this is neccessary because ReadyExecd forks
-      # and RNG in a child process got the same seed from the parent
-      # after every fork.
-      random.seed()
-
       # Reopen the global persistent dictionary
       global_db = shelve.open(global_db_name, 'w')
 
@@ -201,46 +192,68 @@ def run():
             break
       global_db[image_name] = current_time
 
-      border = random.choice(borders)
-      root, ext = os.path.splitext(image_name)
-
       # Save filename
       if global_db.has_key(filename_key):
          global_db[old_filename_key] = global_db[filename_key]
       global_db[filename_key] = image_name
 
-      placement_options = []
-      if use_PIL:
-         image = Image.open(image_name, 'r')
-         im_w, im_h = image.size
-         del image
-         if (im_w > screen_width) or (im_h > screen_height):
-            zoom = min(screen_width*100//im_w, screen_height*100//im_h)
-            if zoom > 0: placement_options = ["-zoom", str(zoom)]
+      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)
+      flock(lock_file, LOCK_UN)
       lock_file.close()
       # Flush and close the global persistent dictionary
       if global_db: global_db.close()
 
-
-   if ext.lower() in (".bmp", ".png"):
-      # xsetbg does not recognize BMP files.
-      # PNG files have gamma settings, and xli can adapt it to the display gamma;
-      # xloadimage/xview/xsetbg display them with wrong gamma.
-      program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
-         ["-center", "-border", border, image_name]
-      os.execlp(*program_options)
-      error("cannot execute xli!")
-   else:
-      # ...but xli failed to load many image types, use xsetbg for them
-      program_options = ["xsetbg", "xsetbg"] + placement_options + \
-         ["-center", "-border", border, image_name]
-      os.execlp(*program_options)
-      error("cannot execute xsetbg!")
-
-
-if __name__ == "__main__":
-   run()
+@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']
+
+    try:
+        commands[command]()
+    except:
+        status = '500 Error'
+        response_headers = [('Content-type', 'text/plain')]
+        start_response(status, response_headers)
+        return ['Error occured!\n']
+
+    status = '200 OK'
+    response_headers = [('Content-type', 'text/plain')]
+    start_response(status, response_headers)
+    return ['Ok\n']
+
+force()
+httpd = make_server(host, port, app, server_class=QuitWSGIServer)
+httpd.serve_forever()