From: Greg Darke Date: Wed, 16 Jul 2008 07:05:08 +0000 (+1000) Subject: Automated merge with ssh://hg@kagami.tsukasa.net.au/bg_scripts/ X-Git-Url: https://code.delx.au/bg-scripts/commitdiff_plain/a407e8b413e333ac956dd54e600f7868ab1b57a8?hp=f2554cc07990a990e373bf499e9b0a40dccfe7c9 Automated merge with ssh://hg@kagami.tsukasa.net.au/bg_scripts/ --- diff --git a/ncat.py b/ncat.py deleted file mode 100755 index b9314ea..0000000 --- a/ncat.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python - -import sys, os, os.path, socket -from optparse import OptionParser, Values - -VERSION = '''$Revision$''' - -try: - # These are my libraries... - import GregDebug, AsyncSocket - - from GregDebug import debug, setDebugLevel, DEBUG_LEVEL_DEBUG, DEBUG_LEVEL_LOW, DEBUG_LEVEL_MEDIUM, DEBUG_LEVEL_HIGH, DEBUG_INCREMENT -except ImportError, e: - print >>sys.stderr, "Missing libraries!\nExiting..." - sys.exit(1) - - -class NetClient(object): - def __init__(self): - self.async_handler = AsyncSocket.AsyncSocketOwner() - - def buildparser(self): - parser = OptionParser(version="%prog " + VERSION, - description = "Connects to a specific server", - usage = "%prog [options] server [port]") - parser.add_option("-U", "--domain-socket", - action="store_true", dest="isUnixDomainSocket", default="", - help="Make the connection over a unix domain socket") - 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)") - return parser - - def createUnixSocket(self, domainSocketName): - sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - sock.connect(domainSocketName) - return sock - - def __handleStdin(self, fd): - data = fd.read() - if not data: - debug('Seems that stdin has been closed (got no data from in on the last read) - exiting main loop') - self.async_handler.exit() #XXX: I think this is the correct name - self.remoteSock.send(data) # Write the data to the socket - # TODO: Make sure that the data written to the socket has been completly written - Since - # self.sock is in non-blocking mode it may not have send everything - - def __handleSock(self, fd): - data = fd.read() - if not data: - debug('Seems that the socket has been closed (got no data from in on the last read) - exiting main loop') - self.async_handler.doExit() #XXX: I think this is the correct name - sys.stdout.write(data) # Write the data to the screen - sys.stdout.flush() - # TODO: Turn sys.stdout into a non-blocking socket, since this call could block, and make things - # non-responsive - - def main(self): - parser = self.buildparser() - useroptions, params = parser.parse_args(sys.argv[1:]) - - setDebugLevel(DEBUG_INCREMENT * (useroptions.quiet - useroptions.verbose)) - debug("Just set GregDebug.DEBUG_LEVEL to %d" % GregDebug.DEBUG_LEVEL, DEBUG_LEVEL_LOW) - - if useroptions.isUnixDomainSocket: - self.remoteSock = self.createUnixSocket(params[0]) - else: - print >>sys.stderr, "No connection type specified" - sys.exit(1) - - self.async_handler.addFD(sys.stdin, self.__handleStdin) - self.async_handler.addSocket(self.remoteSock, self.__handleSock) - self.async_handler.mainLoop() - -if __name__ == "__main__": - NetClient().main() diff --git a/python24_adapter.py b/python24_adapter.py deleted file mode 100644 index 28951e1..0000000 --- a/python24_adapter.py +++ /dev/null @@ -1,20 +0,0 @@ -#! python - -import collections - -class defaultdict(dict): - def __init__(self, default_factory): - self.default_factory = default_factory - def __missing__(self, key): - if self.default_factory is None: - raise KeyError(key) - self[key] = value = self.default_factory() - return value - def __getitem__(self, key): - try: - return dict.__getitem__(self, key) - except KeyError: - return self.__missing__(key) - -if not hasattr(collections, 'defaultdict'): - collections.defaultdict = defaultdict diff --git a/randombg.py b/randombg.py index bb4050c..3deac9c 100755 --- a/randombg.py +++ b/randombg.py @@ -7,7 +7,6 @@ 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: import cPickle as pickle @@ -19,7 +18,7 @@ try: import asyncsched import wallchanger except ImportError, e: - critical("Missing libraries! Exiting...") + logging.critical("Missing libraries! Exiting...") sys.exit(1) @@ -42,16 +41,16 @@ class BaseFileList(object): def store_cache(self, filename): try: - debug("Attempting to store cache") + logging.debug("Attempting to store cache") fd = open(filename, 'wb') pickle.dump(obj = self, file = fd, protocol = 2) - debug("Cache successfully stored") + logging.debug("Cache successfully stored") except Exception, e: warning("Storing cache: %s" % e) def load_cache(self, filename): try: - debug("Attempting to load cache from: %s" % filename) + logging.debug("Attempting to load cache from: %s" % filename) self.paths.sort() fd = open(filename, 'rb') @@ -70,7 +69,7 @@ class BaseFileList(object): return True except Exception, e: - warning("Loading cache: %s" % e) + logging.warning("Loading cache: %s" % e) return False def scan_paths(self): @@ -101,10 +100,14 @@ class RandomFileList(BaseFileList): for filename in filter_images(filenames): self.list.append(os.path.join(dirpath, filename)) + def add_path(self, path): + self.paths.append(path) + logging.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) + logging.debug("Picked file '%s' from list" % self.last_image) return self.last_image def get_current_image(self): @@ -125,16 +128,48 @@ class AllRandomFileList(BaseFileList): # Scan the input directory, and then randomize the file list def scan_paths(self): + logging.debug("Scanning paths") + self.list = [] for path in self.paths: - debug('Scanning "%s"' % path) + logging.debug('Scanning "%s"' % path) for dirpath, dirsnames, filenames in os.walk(path): for filename in filter_images(filenames): - debug('Adding file "%s"' % filename) + logging.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) + logging.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) + 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) + else: + return True + def get_current_image(self): return self.list[self.imagePointer] @@ -146,13 +181,13 @@ class AllRandomFileList(BaseFileList): 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)) + logging.debug("Picked file '%s' (pointer=%d) from list" % (imageName, self.imagePointer)) return imageName 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)) + logging.debug("Picked file '%s' (pointer=%d) from list" % (imageName, self.imagePointer)) return imageName def is_empty(self): @@ -167,25 +202,27 @@ class FolderRandomFileList(BaseFileList): self.last_image = None def scan_paths(self): - for path in self.paths: - 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) - + pass + + def add_path(self, path): + logging.debug('Added path "%s" to the list' % path) + for dirpath, dirs, filenames in os.walk(path): + logging.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 + logging.debug('Adding "%s" to "%s"' % (filenames, dirpath)) + else: + logging.debug("No images found in '%s'" % dirpath) + def get_next_image(self): directory = random.choice(self.directories.keys()) - debug('directory: "%s"' % directory) + logging.debug('directory: "%s"' % directory) filename = random.choice(self.directories[directory]) - debug('filename: "%s"' % filename) - self.last_image = os.path.join(directory, filename) - return self.last_image + logging.debug('filename: "%s"' % filename) + return os.path.join(directory, filename) def get_current_image(self): if self.last_image: @@ -202,10 +239,10 @@ class Cycler(object): self.cycle_time = options.cycle_time self.history_filename = options.history_filename - debug("Initialising wallchanger") + logging.debug("Initialising wallchanger") wallchanger.init(options.background_colour, options.permanent) - debug("Initialising file list") + logging.debug("Initialising file list") if options.all_random: self.filelist = AllRandomFileList() elif options.folder_random: @@ -217,13 +254,13 @@ class Cycler(object): self.filelist.add_path(path) if self.filelist.load_cache(self.history_filename): - debug("Loaded cache successfully") + logging.debug("Loaded cache successfully") else: - debug("Could not load cache") + logging.debug("Could not load cache") self.filelist.scan_paths() if self.filelist.is_empty(): - error("No images were found. Exiting...") + logging.error("No images were found. Exiting...") sys.exit(1) self.task = None @@ -245,7 +282,7 @@ class Cycler(object): 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) + logging.debug("Reset timer for %s seconds" % self.cycle_time) def cmd_reload(self): image = self.filelist.get_current_image() @@ -288,13 +325,13 @@ class Server(asynchat.async_chat): self.ibuffer = [] prefix, cmd = line.split(None, 1) if prefix != "cmd": - debug('Bad line received "%s"' % line) + logging.debug('Bad line received "%s"' % line) return if hasattr(self.cycler, "cmd_" + cmd): - debug('Executing command "%s"' % cmd) + logging.debug('Executing command "%s"' % cmd) getattr(self.cycler, "cmd_" + cmd)() else: - debug('Unknown command received "%s"' % cmd) + logging.debug('Unknown command received "%s"' % cmd) @@ -340,7 +377,7 @@ def do_client(options, args): sock = sock.makefile() for i, cmd in enumerate(args): sock.write("cmd %s\n" % cmd) - if i+1 != len(args): + if i < len(args) - 1: time.sleep(options.cycle_time) sock.close() diff --git a/wallchanger.py b/wallchanger.py index 16e7230..5982621 100755 --- a/wallchanger.py +++ b/wallchanger.py @@ -5,7 +5,7 @@ # This is a cross platform/cross window manager way to change your wallpaper import commands, sys, os, os.path, subprocess, time -from logging import debug, info, warning +import logging __all__ = ("init", "set_image") @@ -13,15 +13,15 @@ __all__ = ("init", "set_image") changers = [] def set_image(filename): - info("Setting image: %s" % filename) + logging.info("Setting image: %s", filename) for changer in changers: if not changer.set_image(filename): - warning("Failed to set background: wallchanger.set_image(%s), changer=%s" % (filename, changer)) + logging.warning("Failed to set background: wallchanger.set_image(%s), changer=%s", filename, changer) def init(*args, **kwargs): """Desktop Changer factory""" - debug("Testing for OSX (NonX11)") + logging.debug("Testing for OSX (NonX11)") if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0: changers.append(OSXChanger(*args, **kwargs)) @@ -35,15 +35,15 @@ def init(*args, **kwargs): # X11 is not running for this display return - debug("Testing for KDE") + logging.debug("Testing for KDE") if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0: changers.append(KDEChanger(*args, **kwargs)) - debug("Testing for Gnome") + logging.debug("Testing for Gnome") if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0: changers.append(GnomeChanger(*args, **kwargs)) - debug("Testing for WMaker") + logging.debug("Testing for WMaker") if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0: changers.append(WMakerChanger(*args, **kwargs)) @@ -54,7 +54,7 @@ def init(*args, **kwargs): class BaseChanger(object): name = "undefined" def __init__(self, background_color='black', permanent=False, convert=False): - info('Determined the window manager is "%s"' % self.name) + logging.info('Determined the window manager is "%s"', self.name) self.background_color = background_color self.permanent = permanent self.convert = convert @@ -80,14 +80,14 @@ class WMakerChanger(BaseChanger): self.remove_old_image_cache() output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time()) cmd = ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name] - debug("""Convert command: '"%s"'""" % '" "'.join(cmd)) + logging.debug("""Convert command: '"%s"'""", '" "'.join(cmd)) return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() def set_image(self, file): if self.convert: file, convert_status = self.convert_image_format(file) if convert_status: - debug('Convert failed') + logging.debug('Convert failed') cmd = ["wmsetbg", "-b", self.background_color, # Sets the background colour to be what the user specified "-S", # 'Smooth' (WTF?) @@ -99,7 +99,7 @@ class WMakerChanger(BaseChanger): if self.permanent: cmd += ["-u"] # update the wmaker database cmd += [file] - debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd)) + logging.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd)) return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() class OSXChanger(BaseChanger): @@ -130,7 +130,7 @@ class OSXChanger(BaseChanger): img.save(output_name, "PNG") return output_name, True except ImportError: - debug('Could not load PIL, going to try just copying the image') + logging.debug('Could not load PIL, going to try just copying the image') import shutil output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(file)) shutil.copyfile(file, output_name) @@ -149,24 +149,24 @@ class OSXChanger(BaseChanger): # Store the plist again (Make sure we write it out atomically -- Don't want to break finder) desktop_plist.writeToFile_atomically_(self._DesktopPlistLocation, True) except ImportError: - debug('Could not import the Foundation module, you may have problems with dual screens') + logging.debug('Could not import the Foundation module, you may have problems with dual screens') def set_image(self, filename): self.fix_desktop_plist() if self.convert: filename, ret = self.convert_image_format(filename) if not ret: - debug("Convert failed") + logging.debug("Convert failed") return False cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename - debug(cmd) + logging.debug(cmd) return not commands.getstatusoutput(cmd)[0] class GnomeChanger(BaseChanger): name = "Gnome" def set_image(self, file): cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file] - debug(cmd) + logging.debug(cmd) return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() class KDEChanger(BaseChanger): @@ -182,7 +182,7 @@ class KDEChanger(BaseChanger): cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure']) for cmd in cmds: - debug(cmd) + logging.debug(cmd) if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0: return False @@ -190,7 +190,6 @@ class KDEChanger(BaseChanger): def main(filename): - import logging logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") init() set_image(filename)