]> code.delx.au - bg-scripts/blobdiff - lib/WallChanger.py
Moved randombg2 to a sensiable name
[bg-scripts] / lib / WallChanger.py
index 1fb3e82f587de93ff9b181186391ce05a66e93b3..b7a81ab18fea42e341466fe084f4e5979f9fb682 100644 (file)
@@ -2,6 +2,7 @@
 
 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 FileLists
 
 import python24_adapter # NB: Must be imported before collections
 import collections
@@ -11,8 +12,6 @@ desktop image."""
 
 __all__ = ('RandomBG')
 
-KDE_CONFIG = os.path.expanduser('~/.kde/share/config/kdesktoprc')
-
 def RandomBG(*args, **kwargs):
        """Desktop Changer factory"""
 
@@ -22,7 +21,7 @@ def RandomBG(*args, **kwargs):
        if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
                ret = __OSXChanger(*args, **kwargs)
 
-       if 'DISPLAY' not in os.environ:
+       if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
                # X11 is not running
                return ret
        else:
@@ -39,6 +38,13 @@ def RandomBG(*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:
@@ -75,8 +81,11 @@ class __BaseChanger(object):
                return self.changeTo(file) and self.callChained(file)
        
        def cycleReload(self):
-               file = self.filelist.getCurrentImage()
-               return self.changeTo(file) and self.callChained(file)
+               try:
+                       file = self.filelist.getCurrentImage()
+                       return self.changeTo(file) and self.callChained(file)
+               except FileLists.FileListNotImplemented:
+                       return self.cycleNext()
 
 
 class __WMakerChanger(__BaseChanger):
@@ -118,6 +127,8 @@ class __WMakerChanger(__BaseChanger):
 
 class __OSXChanger(__BaseChanger):
        _ConvertedWallpaperLocation = '/tmp/wallpapers/'
+       _DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
+
        def _removeOldImageCache(self):
                """Cleans up any old temp images"""
                if not os.path.isdir(self._ConvertedWallpaperLocation):
@@ -132,70 +143,64 @@ class __OSXChanger(__BaseChanger):
                """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()
+               try:
+                       import PIL, PIL.Image
+                       img = PIL.Image.open(file)
+                       img.save(output_name, "PNG")
+                       return output_name, True
+               except ImportError:
+                       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)
+                       return output_name, True
+
+       def _fixDesktopPList(self):
+               """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
+               try:
+                       import Foundation
+                       desktopPList = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
+                       # Remove all but the 'default' entry
+                       for k in desktopPList['Background'].keys():
+                               if k == 'default':
+                                       continue
+                               desktopPList['Background'].removeObjectForKey_(k)
+                       # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
+                       desktopPList.writeToFile_atomically_(self._DesktopPlistLocation, True)
+               except ImportError:
+                       debug('Could not import the Foundation module, you may have problems with dual screens', DEBUG_LEVEL_MEDIUM)
 
        def changeTo(self, file):
                output_name, ret = self._convertImageFormat(file)
-               if ret: # Since 0 indicates success
-                       debug("Convert failed %s" % ret)
+               if not ret:
+                       debug("Convert failed")
                        return False
+               self._fixDesktopPList()
                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 _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()
+               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
+