+++ /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')
-
-KDE_CONFIG = os.path.expanduser('~/.kde/share/config/kdesktoprc')
-
-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:
- # 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 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 __KDEChanger(__BaseChanger):
- def _parseKDEConfig(self, filename = KDE_CONFIG):
- fd = open(filename, 'r')
- result = collection.defaultdict(dict)
- section = None
- for line in fd:
- line = line.strip()
- if not line or line.startswith('#'):
- continue
-
- if line.startswith('[') and line.endswith(']'):
- section = line[1:-1]
- result[section] = {}
- continue
- elif not section:
- raise Exception('Invalid kdesktoprc file')
-
- unpack = line.split('=', 1)
- if len(unpack) == 2:
- key, val = unpack
- else:
- key, val = unpack[0], None
- result[section][key] = val
-
- fd.close()
- return result
-
- def _writeKDEConfig(self, config, filename = KDE_CONFIG):
- fd = open(filename, 'w')
- for section, values in config.items():
- print >>fd, '[%s]' % section
- for k, v in values.items():
- if v != None:
- print >>fd, '%s=%s' % (k,v)
- else:
- print >>fd, k
- print >>fd
- fd.close()
-
- def changeTo(self, file):
- kdeconfig = self._parseKDEConfig()
- #kdeconfig['Background Common']['DrawBackgroundPerScreen_0']='true'
- for section in ('Desktop0', 'Desktop0Screen0'):
- kdeconfig[section]['Wallpaper'] = file
- kdeconfig[section]['UseSHM'] = 'true'
- kdeconfig[section]['WallpaperMode'] = 'ScaleAndCrop'
- # Ensure that random mode is disabled...
- if 'MultiWallpaperMode' in kdeconfig[section]:
- del kdeconfig[section]['MultiWallpaperMode']
-
- self._writeKDEConfig(kdeconfig)
-
- return not subprocess.Popen(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'],
- stdout=sys.stdout, stderr=sys.stderr, stdin=open('/dev/null', 'r')).wait()