-#!/usr/bin/env python
+#!/usr/bin/env python2
+
# Copyright 2008 Greg Darke <greg@tsukasa.net.au>
# Copyright 2008 James Bunton <jamesbunton@fastmail.fm>
# Licensed for distribution under the GPL version 2, check COPYING for details
if not changer.set_image(filename):
logging.warning("Failed to set background: wallchanger.set_image(%s), changer=%s", filename, changer)
+def check_cmd(cmd):
+ return commands.getstatusoutput(cmd)[0] == 0
+
def init(*args, **kwargs):
"""Desktop Changer factory"""
+ classes = []
+
if sys.platform == "win32":
- changers.append(WIN32Changer(*args, **kwargs))
+ classes.append(WIN32Changer)
return
logging.debug("Testing for OSX (NonX11)")
- if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
- changers.append(OSXChanger(*args, **kwargs))
+ if check_cmd("ps ax -o command -c|grep -q WindowServer"):
+ classes.append(OSXChanger)
if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
# X11 is not running
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 check_cmd("ps ax -o command|grep -q '^/.*X11 .* %s'" % os.environ['DISPLAY']):
# X11 is not running for this display
return
- logging.debug("Testing for KDE")
- if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
- changers.append(KDEChanger(*args, **kwargs))
+ logging.debug("Testing for XFCE4")
+ if check_cmd("xwininfo -name 'xfce4-session'"):
+ classes.append(Xfce4Changer)
logging.debug("Testing for Gnome")
- if commands.getstatusoutput("xwininfo -name 'gnome-settings-daemon'")[0] == 0:
- changers.append(GnomeChanger(*args, **kwargs))
-
- logging.debug("Testing for WMaker")
- if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
- changers.append(WMakerChanger(*args, **kwargs))
-
- if len(changers) == 0:
+ if check_cmd("xwininfo -name 'gnome-settings-daemon'"):
+ if check_cmd("gsettings get org.gnome.desktop.background picture-uri"):
+ classes.append(Gnome3Changer)
+ else:
+ classes.append(Gnome2Changer)
+
+ logging.debug("Testing for xloadimage")
+ if check_cmd("which xloadimage"):
+ classes.append(XLoadImageChanger)
+
+ if len(classes) == 0:
raise Exception("Unknown window manager")
+ for klass in classes:
+ changers.append(klass(*args, **kwargs))
+
class BaseChanger(object):
name = "undefined"
- def __init__(self, background_color='black', permanent=False, convert=False):
+ def __init__(self, background_color='black', convert=False):
logging.info('Determined the window manager is "%s"', self.name)
self.background_color = background_color
- self.permanent = permanent
self.convert = convert
- try:
+ try:
+ def _exec_cmd(self, cmd):
import subprocess
- except ImportError:
- self._runProgram = self._runProgram_command
- else:
- self._runProgram = self._runProgram_subprocess
+ return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
- 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)
+ except ImportError:
+ # A simple implementation of subprocess for python2.4
+ def _exec_cmd(self, cmd):
+ """Runs a program given in cmd"""
+ return os.spawnvp(os.P_WAIT, cmd[0], cmd)
def set_image(self, filename):
raise NotImplementedError()
return output_name, True
-class WMakerChanger(BaseChanger):
- name = "WindowMaker"
- _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
+class XLoadImageChanger(BaseChanger):
+ name = "xloadimage"
+ _ConvertedWallpaperLocation = '/tmp/wallpapers_xloadimage/'
def remove_old_image_cache(self):
"""Cleans up any old temp images"""
if not os.path.isdir(self._ConvertedWallpaperLocation):
for dirname in dirnames:
os.unlink(os.path.join(fullpath, dirname))
- def convert_image_format(self, file):
+ def convert_image_format(self, filename):
"""Convert the image to a png, and store it in a local place"""
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]
+ cmd = ["convert", filename, output_name]
logging.debug("""Convert command: '"%s"'""", '" "'.join(cmd))
- return output_name, self._runProgram(cmd)
+ return output_name, self._exec_cmd(cmd)
- def set_image(self, file):
+ def set_image(self, filename):
if self.convert:
- file, convert_status = self.convert_image_format(file)
+ filename, convert_status = self.convert_image_format(filename)
if convert_status:
logging.debug('Convert failed')
- cmd = ["wmsetbg",
- "-b", self.background_color, # 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]
+ cmd = [
+ "xloadimage",
+ "-onroot",
+ "-fullscreen",
+ "-border", "black",
+ filename,
+ ]
logging.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd))
- return not self._runProgram(cmd)
+ return not self._exec_cmd(cmd)
class OSXChanger(BaseChanger):
name = "Mac OS X"
for dirname in dirnames:
os.unlink(os.path.join(fullpath, dirname))
- def convert_image_format(self, file):
+ def convert_image_format(self, filename):
"""Convert the image to a png, and store it in a local place"""
self.remove_old_image_cache()
output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
try:
- return super(OSXChanger, self).convert_image_format(file, format='PNG', extension='.png')
+ return super(OSXChanger, self).convert_image_format(filename, format='PNG', extension='.png')
except ImportError:
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)
+ output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(filename))
+ shutil.copyfile(filename, output_name)
return output_name, True
def fix_desktop_plist(self):
)
return True
-class GnomeChanger(BaseChanger):
+class Gnome2Changer(BaseChanger):
name = "Gnome"
- def set_image(self, file):
- cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
+ def set_image(self, filename):
+ cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', filename]
logging.debug(cmd)
- return not self._runProgram(cmd)
-
-class KDEChanger(BaseChanger):
- name = "KDE"
- def set_image(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:
- logging.debug(cmd)
- if self._runProgram(cmd) != 0:
- return False
+ return not self._exec_cmd(cmd)
- return True
+class Gnome3Changer(BaseChanger):
+ name = "Gnome3"
+ def set_image(self, filename):
+ cmd = ['gsettings', 'set', 'org.gnome.desktop.background', 'picture-uri', 'file://'+filename]
+ logging.debug(cmd)
+ return not self._exec_cmd(cmd)
+class Xfce4Changer(BaseChanger):
+ name = "XFCE4"
+ def set_image(self, filename):
+ cmd = [
+ "xfconf-query",
+ "-c", "xfce4-desktop",
+ "-p", "/backdrop/screen0/monitor0/image-path",
+ "-s", filename,
+ ]
+ logging.debug(cmd)
+ return not self._exec_cmd(cmd)
def main(filename):
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")