X-Git-Url: https://code.delx.au/bg-scripts/blobdiff_plain/19e6816dfcc991fd4f00e6f0f389975703c638f4..deb3e40c103b740dac866e4d2b3de00114b9ba9e:/randombg.py diff --git a/randombg.py b/randombg.py index fff408f..51f6f72 100755 --- a/randombg.py +++ b/randombg.py @@ -1,10 +1,15 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 -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 try: @@ -65,10 +70,11 @@ class BaseFileList(object): if tmp.__class__ != self.__class__: raise ValueError("Using different file list type") - self.paths.sort() - if self.paths != getattr(tmp, "paths"): - raise ValueError("Path list changed") + 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) @@ -162,24 +168,6 @@ class AllRandomFileList(BaseFileList): 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', 'favourites'): - 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) - else: - return True - def get_current_image(self): return self.list[self.imagePointer] @@ -203,6 +191,7 @@ 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.""" @@ -247,10 +236,10 @@ class FolderRandomFileList(BaseFileList): class Cycler(object): 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, options.convert) + wallchanger.init(options.background_colour, options.convert) logging.debug("Initialising file list") if options.all_random: @@ -263,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") @@ -280,7 +269,7 @@ class Cycler(object): 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 @@ -296,7 +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.history_filename) + self.filelist.store_cache(self.cache_filename) def cmd_reload(self): image = self.filelist.get_current_image() @@ -328,8 +317,8 @@ class Cycler(object): 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") @@ -351,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): @@ -361,8 +358,8 @@ 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 @@ -370,21 +367,29 @@ class Listener(asyncore.dispatcher): def do_server(options, paths): try: - cycler = Cycler() - listener = Listener(options.socket_filename, cycler) - # Initialisation of Cycler delayed so we grab the socket quickly - cycler.init(options, paths) - try: - asyncsched.loop() - except KeyboardInterrupt: - print - cycler.finish() - finally: - # Make sure that the socket is cleaned up - try: - os.unlink(options.socket_filename) - except: - pass + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.connect(options.socket_filename) + print >>sys.stderr, "Server is already running! Sending exit command." + sock = sock.makefile() + sock.write("cmd exit\n") + sock.close() + except Exception, e: + pass + + try: + os.unlink(options.socket_filename) + except OSError: + pass + + cycler = Cycler() + listener = Listener(options.socket_filename, cycler) + # Initialisation of Cycler delayed so we grab the socket quickly + cycler.init(options, paths) + try: + asyncsched.loop() + except KeyboardInterrupt: + print + cycler.finish() def do_client(options, args): if len(args) == 0: @@ -410,9 +415,6 @@ def build_parser(): "\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)") @@ -437,9 +439,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(): @@ -451,15 +456,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) - else: - if os.path.exists(options.socket_filename): - do_client(options, args) - else: - do_server(options, args) + return + + try: + do_client(options, args) + return + except Exception, e: + print >>sys.stderr, "Failed to connect to server:", e if __name__ == "__main__": main() -