]> code.delx.au - bg-scripts/blobdiff - wallchanger.py
Automated merge with ssh://hg@kagami.tsukasa.net.au/bg_scripts/
[bg-scripts] / wallchanger.py
index 16e7230781a5134154324bcd02d2b8070e759bba..6c2ba004c3b14ad0a69b5909c62b7242c899c6ce 100755 (executable)
@@ -4,8 +4,8 @@
 # Licensed for distribution under the GPL version 2, check COPYING for details
 # 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 commands, sys, os, os.path, time
+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))
 
@@ -31,19 +31,19 @@ def init(*args, **kwargs):
        else:
                if os.uname()[0] == 'Darwin':
                        # Try to detect if the X11 server is running on OSX
-                       if commands.getstatusoutput("ps ax -o command|grep -q '/.*X11 .* %s'" % os.environ['DISPLAY'])[0] != 0:
+                       if commands.getstatusoutput("ps ax -o command|grep -q '^/.*X11 .* %s'" % os.environ['DISPLAY'])[0] != 0:
                                # 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,11 +54,27 @@ 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
 
+               try:
+                       import subprocess
+               except ImportError:
+                       self._runProgram = self._runProgram_command
+               else:
+                       self._runProgram = self._runProgram_subprocess
+
+       def _runProgram_subprocess(self, cmd):
+               import subprocess
+               return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
+
+       # A simple implementation of subprocess for python2.4
+       def _runProgram_command(self, cmd):
+               """Runs a program given in cmd"""
+               return os.spawnvp(os.P_WAIT, cmd[0], cmd)
+
        def set_image(self, filename):
                raise NotImplementedError()
 
@@ -80,14 +96,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))
-               return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
+               logging.debug("""Convert command: '"%s"'""", '" "'.join(cmd))
+               return output_name, self._runProgram(cmd)
 
        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,8 +115,8 @@ class WMakerChanger(BaseChanger):
                if self.permanent:
                        cmd += ["-u"] # update the wmaker database
                cmd += [file]
-               debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd))
-               return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
+               logging.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd))
+               return not self._runProgram(cmd)
 
 class OSXChanger(BaseChanger):
        name = "Mac OS X"
@@ -130,7 +146,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,25 +165,25 @@ 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)
-               return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
+               logging.debug(cmd)
+               return not self._runProgram(cmd)
 
 class KDEChanger(BaseChanger):
        name = "KDE"
@@ -182,15 +198,14 @@ class KDEChanger(BaseChanger):
 
                cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
                for cmd in cmds:
-                       debug(cmd)
-                       if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
+                       logging.debug(cmd)
+                       if self._runProgram(cmd) != 0:
                                return False
 
                return True
 
 
 def main(filename):
-       import logging
        logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
        init()
        set_image(filename)