+++ /dev/null
-#! python
-
-import commands, sys, os, os.path, subprocess, time
-from GregDebug import debug, setDebugLevel, DEBUG_LEVEL_DEBUG, DEBUG_LEVEL_LOW, DEBUG_LEVEL_MEDIUM, DEBUG_LEVEL_HIGH, DEBUG_INCREMENT
-
-import python24_adapter # NB: Must be imported before collections
-import collections
-
-"""This is a cross platform/cross window manager way to change your current
-desktop image."""
-
-__all__ = ('RandomBG')
-
-def RandomBG(*args, **kwargs):
- """Desktop Changer factory"""
-
- ret = None
-
- debug("Testing for OSX (NonX11)", DEBUG_LEVEL_LOW)
- if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
- ret = __OSXChanger(*args, **kwargs)
-
- if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
- # X11 is not running
- return ret
- 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:
- # X11 is not running for this display
- return ret
-
- debug("Testing for KDE", DEBUG_LEVEL_LOW)
- if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
- if ret is not None:
- ret.nextChanger = __KDEChanger(*args, **kwargs)
- else:
- ret = __KDEChanger(*args, **kwargs)
-
- debug("Testing for Gnome", DEBUG_LEVEL_LOW)
- if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
- if ret is not None:
- ret.nextChanger = __GnomeChanger(*args, **kwargs)
- else:
- ret = __GnomeChanger(*args, **kwargs)
-
- debug("Testing for WMaker", DEBUG_LEVEL_LOW)
- if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
- if ret is not None:
- ret.nextChanger = __WMakerChanger(*args, **kwargs)
- else:
- ret = __WMakerChanger(*args, **kwargs)
-
- if ret is None:
- raise Exception("Unknown window manager")
- else:
- return ret
-
-class __BaseChanger(object):
- def __init__(self, filelist, backgroundColour='black', permanent=False):
- debug('Determined the window manager is "%s"' % self.__class__.__name__, DEBUG_LEVEL_MEDIUM)
- self.backgroundColour = backgroundColour
- self.permanent = permanent
- self.filelist = filelist
- # Used to 'chain' background changers
- self.nextChanger = None
-
- def callChained(self, filename):
- if self.nextChanger is None:
- return True
- else:
- return self.nextChanger.changeTo(filename)
-
- def cycleNext(self):
- file = self.filelist.getNextRandomImage()
- return self.changeTo(file) and self.callChained(file)
-
- def cyclePrev(self):
- file = self.filelist.getPrevRandomImage()
- return self.changeTo(file) and self.callChained(file)
-
- def cycleReload(self):
- file = self.filelist.getCurrentImage()
- return self.changeTo(file) and self.callChained(file)
-
-
-class __WMakerChanger(__BaseChanger):
- _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
- def _removeOldImageCache(self):
- """Cleans up any old temp images"""
- if not os.path.isdir(self._ConvertedWallpaperLocation):
- os.mkdir(self._ConvertedWallpaperLocation)
- for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
- for filename in filenames:
- os.unlink(os.path.join(fullpath, filename))
- for dirname in dirnames:
- os.unlink(os.path.join(fullpath, dirname))
-
- def _convertImageFormat(self, file):
- """Convert the image to a png, and store it in a local place"""
- self._removeOldImageCache()
- 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), DEBUG_LEVEL_DEBUG)
- return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
- def changeTo(self, file):
- file, convert_status = self._convertImageFormat(file)
- if convert_status:
- debug('Convert failed')
- cmd = ["wmsetbg",
- "-b", self.backgroundColour, # Sets the background colour to be what the user specified
- "-S", # 'Smooth' (WTF?)
- "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
-### "-a", # scale the image, keeping the aspect ratio
- "-u", # Force this to be the default background
- "-d" # dither
- ]
- if self.permanent:
- cmd += ["-u"] # update the wmaker database
- cmd += [file]
- debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd), DEBUG_LEVEL_DEBUG)
- return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
-
-class __OSXChanger(__BaseChanger):
- _ConvertedWallpaperLocation = '/tmp/wallpapers/'
- def _removeOldImageCache(self):
- """Cleans up any old temp images"""
- if not os.path.isdir(self._ConvertedWallpaperLocation):
- os.mkdir(self._ConvertedWallpaperLocation)
- for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
- for filename in filenames:
- os.unlink(os.path.join(fullpath, filename))
- for dirname in dirnames:
- os.unlink(os.path.join(fullpath, dirname))
-
- def _convertImageFormat(self, file):
- """Convert the image to a png, and store it in a local place"""
- self._removeOldImageCache()
- output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
- cmd = ["convert", file, output_name]
- debug("""Convert command: '"%s"'""" % '" "'.join(cmd), DEBUG_LEVEL_DEBUG)
- return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
-
- def changeTo(self, file):
- output_name, ret = self._convertImageFormat(file)
- if ret: # Since 0 indicates success
- debug("Convert failed %s" % ret)
- return False
- cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
- debug(cmd, DEBUG_LEVEL_DEBUG)
- return not commands.getstatusoutput(cmd)[0]
-
-class __GnomeChanger(__BaseChanger):
- def changeTo(self, file):
- cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
- debug(cmd, DEBUG_LEVEL_DEBUG)
- return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
-
-class __KDEChanger(__BaseChanger):
- def changeTo(self, file):
- cmds = []
- for group in ('Desktop0', 'Desktop0Screen0'):
- base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
- cmds.append(base + ['Wallpaper', file])
- cmds.append(base + ['UseSHM', '--type', 'bool', 'true'])
- cmds.append(base + ['WallpaperMode', 'ScaleAndCrop'])
- cmds.append(base + ['MultiWallpaperMode', 'NoMulti'])
-
- cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
- for cmd in cmds:
- debug(cmd, DEBUG_LEVEL_DEBUG)
- if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
- return 1 # Fail
-
- return 0 # Success
-