X-Git-Url: https://code.delx.au/bg-scripts/blobdiff_plain/5f9578e04b4023f580643c388cfa7a3f2baa7990..0736e53c6d6e9f192c8cbf68602f4a18c0264501:/randombg.py diff --git a/randombg.py b/randombg.py index 3f1609c..9ff4642 100755 --- a/randombg.py +++ b/randombg.py @@ -1,13 +1,23 @@ #!/usr/bin/env python -VERSION = "2.0" +VERSION = "2.1" -import asyncore, asynchat, socket -import os, os.path, random, sys, time +import asyncore +import asynchat +import socket +import os +import random +import sys +import time from optparse import OptionParser import logging -logging.basicConfig(format="%(levelname)s: %(message)s") +try: + logging.basicConfig(format="%(levelname)s: %(message)s") +except TypeError: +# Python 2.3's logging.basicConfig does not support parameters + logging.basicConfig() + try: import cPickle as pickle except ImportError: @@ -18,7 +28,7 @@ try: import asyncsched import wallchanger except ImportError, e: - logging.critical("Missing libraries! Exiting...") + logging.critical("Missing libraries! Exiting...", exc_info=1) sys.exit(1) @@ -33,17 +43,53 @@ def filter_images(filenames): class BaseFileList(object): """Base file list implementation""" - def scan_paths(self): - raise NotImplementedError() + def __init__(self): + self.paths = [] + self.favourites = [] def add_path(self, path): - raise NotImplementedError() + self.paths.append(path) - def store_cache(self, path): - pass + def store_cache(self, filename): + try: + logging.debug("Attempting to store cache") + fd = open(filename, 'wb') + pickle.dump(self, fd, 2) + logging.debug("Cache successfully stored") + except Exception, e: + warning("Storing cache: %s" % e) - def load_cache(self, filename, rescanPaths = False): - pass + def load_cache(self, filename): + try: + logging.debug("Attempting to load cache from: %s" % filename) + self.paths.sort() + + fd = open(filename, 'rb') + tmp = pickle.load(fd) + + if tmp.__class__ != self.__class__: + raise ValueError("Using different file list type") + + tmp.paths.sort() + if self.paths != tmp.paths: + raise ValueError, "Path list changed" + + # Overwrite this object with the other + for attr, value in tmp.__dict__.items(): + setattr(self, attr, value) + + return True + + except Exception, e: + logging.warning("Loading cache: %s" % e) + return False + + def add_to_favourites(self): + '''Adds the current image to the list of favourites''' + self.favourites.append(self.get_current_image()) + + def scan_paths(self): + raise NotImplementedError() def get_next_image(self): raise NotImplementedError() @@ -60,8 +106,8 @@ class BaseFileList(object): class RandomFileList(BaseFileList): def __init__(self): + super(RandomFileList, self).__init__() self.list = [] - self.paths = [] self.last_image = None def scan_paths(self): @@ -80,14 +126,20 @@ class RandomFileList(BaseFileList): logging.debug("Picked file '%s' from list" % self.last_image) return self.last_image + def get_current_image(self): + if self.last_image: + return self.last_image + else: + return self.get_next_image() + def is_empty(self): return len(self.list) == 0 class AllRandomFileList(BaseFileList): def __init__(self): + super(AllRandomFileList, self).__init__() self.list = None - self.paths = [] self.imagePointer = 0 # Scan the input directory, and then randomize the file list @@ -111,27 +163,11 @@ class AllRandomFileList(BaseFileList): def store_cache(self, filename): try: fd = open(filename, 'wb') - pickle.dump(obj = self, file = fd, protocol = 2) + pickle.dump(self, fd, 2) logging.debug("Cache successfully stored") except Exception, e: logging.warning("Storing cache", exc_info=1) - def load_cache(self, filename, rescanPaths = False): - logging.debug('Attempting to load cache from "%s"' % filename) - self.paths.sort() - try: - fd = open(filename, 'rb') - tmp = pickle.load(fd) - if self.paths == tmp.paths: - logging.debug("Path lists match, copying properties") - # Overwrite this object with the other - for attr in ('list', 'imagePointer'): - setattr(self, attr, getattr(tmp, attr)) - else: - logging.debug("Ignoring cache, path lists do not match") - except Exception, e: - logging.warning("Loading cache", exc_info=1) - def get_current_image(self): return self.list[self.imagePointer] @@ -155,11 +191,14 @@ class AllRandomFileList(BaseFileList): def is_empty(self): return len(self.list) == 0 + 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): + super(FolderRandomFileList, self).__init__() self.directories = {} + self.last_image = None def scan_paths(self): pass @@ -184,17 +223,23 @@ class FolderRandomFileList(BaseFileList): logging.debug('filename: "%s"' % filename) return os.path.join(directory, filename) + def get_current_image(self): + if self.last_image: + return self.last_image + else: + return self.get_next_image() + def is_empty(self): return len(self.directories.values()) == 0 class Cycler(object): - def init(self, options, paths): + def init(self, options, paths, oneshot=False): self.cycle_time = options.cycle_time - self.history_filename = options.history_filename + self.cache_filename = options.cache_filename logging.debug("Initialising wallchanger") - wallchanger.init(options.background_colour, options.permanent) + wallchanger.init(options.background_colour, options.permanent, options.convert) logging.debug("Initialising file list") if options.all_random: @@ -207,7 +252,7 @@ class Cycler(object): for path in paths: self.filelist.add_path(path) - if self.filelist.load_cache(self.history_filename): + if self.filelist.load_cache(self.cache_filename): logging.debug("Loaded cache successfully") else: logging.debug("Could not load cache") @@ -218,10 +263,13 @@ class Cycler(object): sys.exit(1) self.task = None - self.cmd_reload() + if oneshot: + self.cmd_next() + else: + self.cmd_reload() def finish(self): - self.filelist.store_cache(self.history_filename) + self.filelist.store_cache(self.cache_filename) def find_files(self, options, paths): return filelist @@ -237,6 +285,7 @@ class Cycler(object): self.task.cancel() self.task = asyncsched.schedule(self.cycle_time, next) logging.debug("Reset timer for %s seconds" % self.cycle_time) + self.filelist.store_cache(self.cache_filename) def cmd_reload(self): image = self.filelist.get_current_image() @@ -255,7 +304,6 @@ class Cycler(object): def cmd_rescan(self): self.filelist.scan_paths() - self.cmd_next() def cmd_pause(self): if self.task is not None: @@ -265,9 +313,12 @@ class Cycler(object): def cmd_exit(self): asyncsched.exit() + def cmd_favourite(self): + self.filelist.add_to_favourites() + class Server(asynchat.async_chat): - def __init__(self, cycler, conn, addr): - asynchat.async_chat.__init__(self, conn=conn) + def __init__(self, cycler, sock): + asynchat.async_chat.__init__(self, sock) self.cycler = cycler self.ibuffer = [] self.set_terminator("\n") @@ -289,6 +340,14 @@ class Server(asynchat.async_chat): logging.debug('Unknown command received "%s"' % cmd) +class SockHackWrap(object): + def __init__(self, sock, addr): + self.__sock = sock + self.__addr = addr + def getpeername(self): + return self.__addr + def __getattr__(self, key): + return getattr(self.__sock, key) class Listener(asyncore.dispatcher): def __init__(self, socket_filename, cycler): @@ -299,14 +358,27 @@ class Listener(asyncore.dispatcher): self.listen(2) # Backlog = 2 def handle_accept(self): - conn, addr = self.accept() - Server(self.cycler, conn, addr) + sock, addr = self.accept() + Server(self.cycler, SockHackWrap(sock, addr)) def writable(self): return False def do_server(options, paths): + try: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.connect(options.socket_filename) + print >>sys.stderr, "Server is already running! Will do nothing" + return + except: + pass + + try: + os.unlink(options.socket_filename) + except OSError: + pass + try: cycler = Cycler() listener = Listener(options.socket_filename, cycler) @@ -321,7 +393,7 @@ def do_server(options, paths): # Make sure that the socket is cleaned up try: os.unlink(options.socket_filename) - except: + except OSError: pass def do_client(options, args): @@ -338,7 +410,7 @@ def do_client(options, args): def do_oneshot(options, paths): cycler = Cycler() - cycler.init(options, paths) + cycler.init(options, paths, oneshot=True) def build_parser(): parser = OptionParser(version="%prog " + VERSION, @@ -375,9 +447,12 @@ def build_parser(): parser.add_option("--socket", action="store", type="string", dest="socket_filename", default=os.path.expanduser('~/.randombg_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'), + parser.add_option("--cache-file", + action="store", type="string", dest="cache_filename", default=os.path.expanduser('~/.randombg_cache'), help="Stores the location of the last image to be loaded.") + parser.add_option("--server", + action="store_true", dest="server", default=False, + help="Run in server mode to listen for clients.") return parser def main(): @@ -389,15 +464,20 @@ def main(): elif options.verbose >= 2: logging.getLogger().setLevel(logging.DEBUG) + if options.server: + do_server(options, args) + return + if options.oneshot: do_oneshot(options, args) + return - if os.path.exists(options.socket_filename): + try: do_client(options, args) - else: - do_server(options, args) + return + except Exception, e: + print >>sys.stderr, "Failed to connect to server:", e if __name__ == "__main__": main() -