]> code.delx.au - bg-scripts/blobdiff - bin/randombg.py
RandomBG: Added oneshot option.
[bg-scripts] / bin / randombg.py
index 7a94fc0febd89e3d67b849739a4dafefb6418a4f..99933fea4fd9879b1c532b98181a413a0b79606e 100755 (executable)
 #!/usr/bin/env python
 
-import sys, os, os.path, socket 
-from optparse import OptionParser, Values
+VERSION = "2.0"
 
-VERSION = "1.1"
-CACHE_LOCATION = os.path.expanduser('~/.randombg2_filelist_cache')
-SOCKET_FILE = os.path.expanduser('~/tmp/tmp_socket')
 
+import asyncore, asynchat, socket
+import os, os.path, random, sys, time
+from optparse import OptionParser
+import logging
+from logging import debug, info, warning, error, critical
+logging.basicConfig(format="%(levelname)s: %(message)s")
 try:
-       # These are my libraries...
-       import GregDebug, AsyncSocket, WallChanger, SigHandler
+       import cPickle as pickle
+except ImportError:
+       import pickle
 
-       from GregDebug import debug, setDebugLevel, DEBUG_LEVEL_DEBUG, DEBUG_LEVEL_LOW, DEBUG_LEVEL_MEDIUM, DEBUG_LEVEL_HIGH, DEBUG_INCREMENT
-
-       from FileLists import *
+try:
+       # Required libraries
+       import asyncsched
+       import wallchanger
 except ImportError, e:
-       print >>sys.stderr, "Missing libraries!\nExiting..."
+       critical("Missing libraries! Exiting...")
        sys.exit(1)
 
-def buildparser():
-       def buildOptions():
+
+
+
+def filter_images(filenames):
+       extensions = ('.jpg', '.jpe', '.jpeg', '.png', '.gif', '.bmp')
+       for filename in filenames:
+               _, ext = os.path.splitext(filename)
+               if ext.lower() in extensions:
+                       yield filename
+
+class BaseFileList(object):
+       """Base file list implementation"""
+       def scan_paths(self):
+               raise NotImplementedError()
+
+       def add_path(self, path):
+               raise NotImplementedError()
+
+       def store_cache(self, path):
                pass
-       def addfilestolist(optclass, opt, value, parser, fileList):
-               fo = open(value)
-               for line in fo:
-                       fileList.list.append(line.strip())
-               fo.close()
-               fileList.allowAllRandom = False
-               
-       parser = OptionParser(version="%prog " + VERSION, 
-               description = "Picks a random background image",
-               usage = "%prog [options] dir [dir2 ...]")
-       parser.add_option("-p", "--permanent",
-               action="store_true", dest="permanent", default=False,
-               help="Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %default]")
-       parser.add_option("-q", "--quiet", "--silent",
-               action="count", dest="quiet", default=0,
-               help="Make the script quiet (good for running from a shell script)")
-       parser.add_option("-v", '-d', "--verbose", "--debug",
-               action="count", dest="verbose", default=0,
-               help="Make the louder (good for debugging, or those who are curious)")
-       parser.add_option("-b", "--background-colour",
-               action="store", type="string", dest="background_colour", default="black",
-               help="Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %default]")
-       parser.add_option("--all-random",
-               action="store_true", dest="all_random", default=False,
-               help="Make sure that all images have been displayed before repeating an image")
-       parser.add_option("--folder-random",
-               action="store_true", dest="folder_random", default=False,
-               help="Give each folder an equal chance of having an image selected from it")
-       #parser.add_option("--file-list",
-       #       action="callback", callback=addfilestolist, type="string", callback_args=(fileList,),
-       #       help="Adds the list of images from the external file")
-       parser.add_option("--cycle",
-               action="store", type="int", default=0, dest="cycle_time",
-               help="Cause the image to cycle every X seconds")
-       return parser
 
+       def load_cache(self, filename, rescanPaths = False):
+               pass
 
-def createIPCClient(domainSocketName):
-       sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-       sock.connect(domainSocketName)
-       sock_file = sock.makefile()
-       return sock_file
+       def get_next_image(self):
+               raise NotImplementedError()
 
-def main():
-       if os.path.exists(SOCKET_FILE):
-               # We are the client
-               sock = createIPCClient(SOCKET_FILE)
-               print >>sock, "CMD NEXT"
-###            print >>sock, "CMD PREVIOUS"
-###            print >>sock, "CMD PAUSE"
-               sock.close()
-       else:
-               # We are the server
+       def get_prev_image(self):
+               raise NotImplementedError()
+
+       def get_current_image(self):
+               raise NotImplementedError()
+
+       def is_empty(self):
+               return False
+
+
+class RandomFileList(BaseFileList):
+       def __init__(self):
+               self.list = []
+               self.paths = []
+               self.last_image = None
+
+       def scan_paths(self):
+               for path in self.paths:
+                       for dirpath, dirsnames, filenames in os.walk(path):
+                               for filename in filter_images(filenames):
+                                       self.list.append(os.path.join(dirpath, filename))
+
+       def add_path(self, path):
+               self.paths.append(path)
+               debug('Added path "%s" to the list' % path)
+
+       def get_next_image(self):
+               n = random.randint(0, len(self.list)-1)
+               self.last_image = self.list[n]
+               debug("Picked file '%s' from list" % self.last_image)
+               return self.last_image
+       
+       def is_empty(self):
+               return len(self.list) > 0
+
+
+class AllRandomFileList(BaseFileList):
+       def __init__(self):
+               self.list = None
+               self.paths = []
+               self.imagePointer = 0
+
+       # Scan the input directory, and then randomize the file list
+       def scan_paths(self):
+               debug("Scanning paths")
+
+               self.list = []
+               for path in self.paths:
+                       debug('Scanning "%s"' % path)
+                       for dirpath, dirsnames, filenames in os.walk(path):
+                               for filename in filter_images(filenames):
+                                       debug('Adding file "%s"' % filename)
+                                       self.list.append(os.path.join(dirpath, filename))
+
+               random.shuffle(self.list)
+
+       def add_path(self, path):
+               self.paths.append(path)
+               debug('Added path "%s" to the list' % path)
+
+       def store_cache(self, filename):
+               try:
+                       fd = open(filename, 'wb')
+                       pickle.dump(obj = self, file = fd, protocol = 2)
+                       debug("Cache successfully stored")
+               except Exception, e:
+                       warning("Exception while storing cache: '%s'" % e)
+
+       def load_cache(self, filename, rescanPaths = False):
+               debug('Attempting to load cache from "%s"' % filename)
+               self.paths.sort()
                try:
-                       Server(SOCKET_FILE)()
-               finally:
-                       # Make sure that the socket is cleaned up
-                       os.unlink(SOCKET_FILE)
+                       fd = open(filename, 'rb')
+                       tmp = pickle.load(fd)
+                       if self.paths == tmp.paths:
+                               debug("Path lists match, copying properties")
+                               # Overwrite this object with the other
+                               for attr in ('list', 'imagePointer'):
+                                       setattr(self, attr, getattr(tmp, attr))
+                       else:
+                               debug("Ignoring cache, path lists do not match")
+               except Exception, e:
+                       warning("Exception while loading cache: '%s'" % e)
+
+       def get_current_image(self):
+               return self.list[self.imagePointer]
+       
+       def __inc_in_range(self, n, amount = 1, rangeMax = None, rangeMin = 0):
+               if rangeMax == None: rangeMax = len(self.list)
+               assert rangeMax > 0
+               return (n + amount) % rangeMax
+
+       def get_next_image(self):
+               self.imagePointer = self.__inc_in_range(self.imagePointer)
+               imageName = self.list[self.imagePointer]
+               debug("Picked file '%s' (pointer=%d) from list" % (imageName, self.imagePointer))
+               return imageName
 
-class Server(object):
-       def __init__(self, domainSocketName):
-               self.socketHandler = self._createIPCServer(domainSocketName)
-               self.callbackObj = None
+       def get_prev_image(self):
+               self.imagePointer = self.__inc_in_range(self.imagePointer, amount=-1)
+               imageName = self.list[self.imagePointer]
+               debug("Picked file '%s' (pointer=%d) from list" % (imageName, self.imagePointer))
+               return imageName
 
-               parser = buildparser()
-               useroptions, paths = parser.parse_args(sys.argv[1:])
+       def is_empty(self):
+               return self.list
 
-               setDebugLevel(DEBUG_INCREMENT * (useroptions.quiet - useroptions.verbose))
-               debug("Just set GregDebug.DEBUG_LEVEL to %d" % GregDebug.DEBUG_LEVEL, DEBUG_LEVEL_LOW)
+class FolderRandomFileList(BaseFileList):
+       """A file list that will pick a file randomly within a directory. Each
+       directory has the same chance of being chosen."""
+       def __init__(self):
+               self.directories = {}
+       
+       def scan_paths(self):
+               pass
+       
+       def add_path(self, path):
+               debug('Added path "%s" to the list' % path)
+               for dirpath, dirs, filenames in os.walk(path):
+                       debug('Scanning "%s" for images' % dirpath)
+                       if self.directories.has_key(dirpath):
+                               continue
+                       filenames = list(filter_images(filenames))
+                       if len(filenames):
+                               self.directories[dirpath] = filenames
+                               debug('Adding "%s" to "%s"' % (filenames, dirpath))
+                       else:
+                               debug("No images found in '%s'" % dirpath)
+       
+       def get_next_image(self):
+               directory = random.choice(self.directories.keys())
+               debug('directory: "%s"' % directory)
+               filename = random.choice(self.directories[directory])
+               debug('filename: "%s"' % filename)
+               return os.path.join(directory, filename)
+       
+       def is_empty(self):
+               return len(self.directories.values())
 
-               self.filelist = self.__getFileList(useroptions, paths)
 
-               if not self.filelist.hasImages():
-                       print >>sys.stderr, "No files!"
-                       parser.print_help()
+class Cycler(object):
+       def init(self, options, paths):
+               self.filelist = self.find_files(options, paths)
+               if not self.filelist.is_empty():
+                       error("No images were found. Exiting...")
                        sys.exit(1)
        
-               debug("Initilizing RandomBG", DEBUG_LEVEL_DEBUG)
-               self.randombg = WallChanger.RandomBG(self.filelist, useroptions.background_colour, useroptions.permanent)
+               debug("Initialising wallchanger")
+               wallchanger.init(options.background_colour, options.permanent)
+               self.cycle_time = options.cycle_time
 
-               # Store some of the other useful options
-               self.cycle_time = useroptions.cycle_time
+               self.task = None
+               self.cmd_next()
 
-       def __getFileList(self, useroptions, paths):
-               if useroptions.all_random:
+       def find_files(self, options, paths):
+               if options.all_random:
                        filelist = AllRandomFileList()
-               elif useroptions.folder_random:
+               elif options.folder_random:
                        filelist = FolderRandomFileList()
                else:
                        filelist = RandomFileList()
 
                for path in paths:
-                       filelist.doAddPath(path)
+                       filelist.add_path(path)
 
-               if filelist.attemptCacheLoad(CACHE_LOCATION):
-                       debug("Loaded cache successfully", DEBUG_LEVEL_LOW)
+               if filelist.load_cache(options.history_filename):
+                       debug("Loaded cache successfully")
                else:
                        debug("Could not load cache")
-                       filelist.doScanPaths()
+                       filelist.scan_paths()
                return filelist
 
-       def cycle_reload(self):
-               debug("Reloading wallpaper", DEBUG_LEVEL_LOW)
-               ret = self.randombg.cycleReload()
-               if not ret:
-                       debug('Could not set wallpaper. Returned "%s"' % ret)
-               debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
-               self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
-               return ret
-
-       def cycle_next(self):
-               debug("Cycling wallpaper", DEBUG_LEVEL_LOW)
-               ret = self.randombg.cycleNext()
-               if not ret:
-                       debug('Could not set wallpaper. Returned "%s"' % ret)
-               debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
-               self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
-               self.filelist.doStoreCache(CACHE_LOCATION)
-               return ret
-
-       def cycle_prev(self):
-               debug("Cycling wallpaper", DEBUG_LEVEL_LOW)
-               ret = self.randombg.cyclePrev()
-               if not ret:
-                       debug('Could not set wallpaper. Returned "%s"' % ret)
-               debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
-               # Yes this is ment to be cycle_next
-               self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
-               self.filelist.doStoreCache(CACHE_LOCATION)
-               return ret
+       def cmd_reset(self):
+               def next():
+                       image = self.filelist.get_next_image()
+                       wallchanger.set_image(image)
+                       self.task = None
+                       self.cmd_reset()
+
+               if self.task is not None:
+                       self.task.cancel()
+               self.task = asyncsched.schedule(self.cycle_time, next)
+               debug("Reset timer for %s seconds" % self.cycle_time)
+       
+       def cmd_reload(self):
+               image = self.filelist.get_current_image()
+               wallchanger.set_image(image)
+               self.cmd_reset()
+
+       def cmd_next(self):
+               image = self.filelist.get_next_image()
+               wallchanger.set_image(image)
+               self.cmd_reset()
+       
+       def cmd_prev(self):
+               image = self.filelist.get_prev_image()
+               wallchanger.set_image(image)
+               self.cmd_reset()
+       
+       def cmd_rescan(self):
+               self.filelist.scan_paths()
+               self.cmd_next()
+       
+       def cmd_pause(self):
+               if self.task is not None:
+                       self.task.cancel()
+                       self.task = None
+
+class Server(asynchat.async_chat):
+       def __init__(self, cycler, conn, addr):
+               asynchat.async_chat.__init__(self, conn=conn)
+               self.cycler = cycler
+               self.ibuffer = []
+               self.set_terminator("\n")
+
+       def collect_incoming_data(self, data):
+               self.ibuffer.append(data)
+       
+       def found_terminator(self):
+               line = "".join(self.ibuffer).lower()
+               self.ibuffer = []
+               prefix, cmd = line.split(None, 1)
+               if prefix != "cmd":
+                       debug('Bad line received "%s"' % line)
+                       return
+               if hasattr(self.cycler, "cmd_" + cmd):
+                       debug('Executing command "%s"' % cmd)
+                       getattr(self.cycler, "cmd_" + cmd)()
+               else:
+                       debug('Unknown command received "%s"' % cmd)
+
+
+
+class Listener(asyncore.dispatcher):
+       def __init__(self, socket_filename, cycler):
+               asyncore.dispatcher.__init__(self)
+               self.cycler = cycler
+               self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
+               self.bind(socket_filename)
+               self.listen(2) # Backlog = 2
+       
+       def handle_accept(self):
+               conn, addr = self.accept()
+               Server(self.cycler, conn, addr)
                
-       def _finished(self):
-               self.filelist.doStoreCache(CACHE_LOCATION)
+
+def do_server(options, paths):
+       try:
+               try:
+                       cycler = Cycler()
+                       listener = Listener(options.socket_filename, cycler)
+                       # Initialisation of Cycler delayed so we grab the socket quickly
+                       cycler.init(options, paths)
+                       asyncsched.loop()
+               except KeyboardInterrupt:
+                       print
+       finally:
+               # Make sure that the socket is cleaned up
+               try:
+                       os.unlink(options.socket_filename)
+               except:
+                       pass
+
+def do_client(options, args):
+       if len(args) == 0:
+               args = ["next"]
+       sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+       sock.connect(options.socket_filename)
+       sock = sock.makefile()
+       for i, cmd in enumerate(args):
+               sock.write("cmd %s\n" % cmd)
+               if i+1 != len(args):
+                       time.sleep(options.cycle_time)
+       sock.close()
+
+def do_oneshot(options, paths):
+       cycler = Cycler()
+       cycler.init(options, paths)
+
+def build_parser():
+       parser = OptionParser(version="%prog " + VERSION, 
+               description = "Cycles through random background images.",
+               usage =
+                       "\n(server) %prog [options] dir [dir2 ...]"
+                       "\n(client) %prog [options] [next|prev|rescan|reload|pause] [...]"
+                       "\nThe first instance to be run will be the server.\n"
+               )
+       parser.add_option("-p", "--permanent",
+               action="store_true", dest="permanent", default=False,
+               help="Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %default]")
+       parser.add_option("-v", '-d', "--verbose", "--debug",
+               action="count", dest="verbose", default=0,
+               help="Make the louder (good for debugging, or those who are curious)")
+       parser.add_option("-b", "--background-colour",
+               action="store", type="string", dest="background_colour", default="black",
+               help="Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %default]")
+       parser.add_option("--all-random",
+               action="store_true", dest="all_random", default=False,
+               help="Make sure that all images have been displayed before repeating an image")
+       parser.add_option("-1", "--oneshot",
+               action="store_true", dest="oneshot", default=False,
+               help="Set one random image and terminate immediately.")
+       parser.add_option("--folder-random",
+               action="store_true", dest="folder_random", default=False,
+               help="Give each folder an equal chance of having an image selected from it")
+       parser.add_option("--cycle-time",
+               action="store", type="int", default=1800, dest="cycle_time",
+               help="Cause the image to cycle every X seconds")
+       parser.add_option("--socket",
+               action="store", type="string", dest="socket_filename", default=os.path.expanduser('~/tmp/tmp_socket'),
+               help="Location of the command/control socket.")
+       parser.add_option("--history-file",
+               action="store", type="string", dest="history_filename", default=os.path.expanduser('~/.randombg_historyfile'),
+               help="Stores the location of the last image to be loaded.")
+       return parser
+
+def main():
+       parser = build_parser()
+       options, args = parser.parse_args(sys.argv[1:])
+
+       if options.verbose == 1:
+               logging.getLogger().setLevel(logging.INFO)
+       elif options.verbose >= 2:
+               logging.getLogger().setLevel(logging.DEBUG)
        
-       def __call__(self):
-               # Callback immediatly
-               self.socketHandler.addCallback(0.0, self.cycle_reload)
-               # Now go into the main loop
-               self.socketHandler.mainLoop()
-               # Clean up time
-               self._finished()
-
-       def _createIPCServer(self, domainSocketName):
-               """Create the Server socket, and start listening for clients"""
-
-               class Handler(object):
-                       def __init__(self, parent):
-                               self.parent = parent
-                       def _removeOldTimer(self):
-                               if self.parent.callbackObj:
-                                       self.parent.socketHandler.removeCallback(self.parent.callbackObj)
-                       def _cmd_PAUSE(self):
-                               debug("Pausing randombg")
-                               self._removeOldTimer()
-                       def _cmd_NEXT(self):
-                               self._removeOldTimer()
-                               self.parent.cycle_next()
-                       def _cmd_PREVIOUS(self):
-                               self._removeOldTimer()
-                               self.parent.cycle_prev()
-                       def _cmd_RESCAN(self):
-                               self.parent.filelist.doScanPaths()
-                               self._cmd_NEXT()
-                       def _cmd_RELOAD(self):
-                               self._removeOldTimer()
-                               self.parent.cycle_reload()
-                       def _processLine(self, line):
-                               prefix, cmd = line.split(None, 1)
-                               if prefix != 'CMD':
-                                       debug('Unknown command received "%s"' % line)
-                                       return
-                               if hasattr(self, '_cmd_%s' % cmd):
-                                       getattr(self, '_cmd_%s' % cmd)()
-                               else:
-                                       debug('Unknown command received "%s"' % cmd)
-                       def __call__(self, lineReader):
-                               try:
-                                       while lineReader.hasLine():
-                                               self._processLine(lineReader.readline())
-                               except Exception, e:
-                                       debug(str(e))
-
-               def handleClient(sock):
-                       conn, address = sock.accept()
-                       async_handler.addLineBufferedSocket(conn, Handler(self) )
-
-               async_handler = AsyncSocket.AsyncSocketOwner()
-
-               sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-               sock.bind(domainSocketName)
-               sock.listen(2) # Backlog = 2
-
-               async_handler.addSocket(sock, handleClient)
-
-               return async_handler
+       if options.oneshot:
+               do_oneshot(options, args)
+
+       if os.path.exists(options.socket_filename):
+               do_client(options, args)
+       else:
+               do_server(options, args)
+
 
 if __name__ == "__main__":
        main()
+