summary |
shortlog |
log |
commit | commitdiff |
tree
raw |
patch |
inline | side by side (from parent 1:
7e127c3)
* Moved lib/WallChanger.py to bin/wallchanger.py
* wallchanger.py now runs standalone to set the desktop background.
* Much better chaining, untested at the moment though.
try:
# Required libraries
import asyncsched
try:
# Required libraries
import asyncsched
except ImportError, e:
critical("Missing libraries! Exiting...")
sys.exit(1)
except ImportError, e:
critical("Missing libraries! Exiting...")
sys.exit(1)
error("No images were found. Exiting...")
sys.exit(1)
error("No images were found. Exiting...")
sys.exit(1)
- debug("Initialising RandomBG")
- self.randombg = WallChanger.RandomBG(options.background_colour, options.permanent)
+ debug("Initialising wallchanger")
+ wallchanger.init(options.background_colour, options.permanent)
self.cycle_time = options.cycle_time
self.task = None
self.cycle_time = options.cycle_time
self.task = None
def cmd_reset(self):
def next():
image = self.filelist.get_next_image()
def cmd_reset(self):
def next():
image = self.filelist.get_next_image()
- self.randombg.setImage(image)
+ wallchanger.set_image(image)
self.task = None
self.cmd_reset()
self.task = None
self.cmd_reset()
def cmd_reload(self):
image = self.filelist.get_current_image()
def cmd_reload(self):
image = self.filelist.get_current_image()
- self.randombg.setImage(image)
+ wallchanger.set_image(image)
self.cmd_reset()
def cmd_next(self):
image = self.filelist.get_next_image()
self.cmd_reset()
def cmd_next(self):
image = self.filelist.get_next_image()
- self.randombg.setImage(image)
+ wallchanger.set_image(image)
self.cmd_reset()
def cmd_prev(self):
image = self.filelist.get_prev_image()
self.cmd_reset()
def cmd_prev(self):
image = self.filelist.get_prev_image()
- self.randombg.setImage(image)
+ wallchanger.set_image(image)
self.cmd_reset()
def cmd_rescan(self):
self.cmd_reset()
def cmd_rescan(self):
class Listener(asyncore.dispatcher):
class Listener(asyncore.dispatcher):
- def __init__(self, socket_filename, randombg):
+ def __init__(self, socket_filename, cycler):
asyncore.dispatcher.__init__(self)
asyncore.dispatcher.__init__(self)
- self.randombg = randombg
self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.bind(socket_filename)
self.listen(2) # Backlog = 2
def handle_accept(self):
conn, addr = self.accept()
self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.bind(socket_filename)
self.listen(2) # Backlog = 2
def handle_accept(self):
conn, addr = self.accept()
- Server(self.randombg, conn, addr)
+ Server(self.cycler, conn, addr)
def do_server(options, paths):
def do_server(options, paths):
+#!/usr/bin/env python
+# 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
+# This is a cross platform/cross window manager way to change your wallpaper
import commands, sys, os, os.path, subprocess, time
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
+from logging import debug, info, warning
-import python24_adapter # NB: Must be imported before collections
-import collections
+__all__ = ("init", "set_image")
-"""This is a cross platform/cross window manager way to change your current
-desktop image."""
-def RandomBG(*args, **kwargs):
- """Desktop Changer factory"""
+def set_image(filename):
+ for changer in changers:
+ if not changer.set_image(filename):
+ 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)", DEBUG_LEVEL_LOW)
+ debug("Testing for OSX (NonX11)")
if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
- ret = __OSXChanger(*args, **kwargs)
+ changers.append(OSXChanger(*args, **kwargs))
if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
# X11 is not running
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:
# X11 is not running for this display
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
- debug("Testing for KDE", DEBUG_LEVEL_LOW)
+ debug("Testing for KDE")
if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
- if ret is not None:
- ret.nextChanger = __KDEChanger(*args, **kwargs)
- else:
- ret = __KDEChanger(*args, **kwargs)
+ changers.append(KDEChanger(*args, **kwargs))
- debug("Testing for Gnome", DEBUG_LEVEL_LOW)
+ debug("Testing for Gnome")
if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
- if ret is not None:
- ret.nextChanger = __GnomeChanger(*args, **kwargs)
- else:
- ret = __GnomeChanger(*args, **kwargs)
+ changers.append(GnomeChanger(*args, **kwargs))
- debug("Testing for WMaker", DEBUG_LEVEL_LOW)
+ debug("Testing for WMaker")
if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
- if ret is not None:
- ret.nextChanger = __WMakerChanger(*args, **kwargs)
- else:
- ret = __WMakerChanger(*args, **kwargs)
+ changers.append(WMakerChanger(*args, **kwargs))
raise Exception("Unknown window manager")
raise Exception("Unknown window manager")
-class __BaseChanger(object):
- def __init__(self, backgroundColour='black', permanent=False):
- debug('Determined the window manager is "%s"' % self.__class__.__name__, DEBUG_LEVEL_MEDIUM)
- self.backgroundColour = backgroundColour
+
+class BaseChanger(object):
+ name = "undefined"
+ def __init__(self, background_color='black', permanent=False):
+ info('Determined the window manager is "%s"' % self.name)
+ self.background_color = background_color
self.permanent = permanent
self.permanent = permanent
- # Used to 'chain' background changers
- self.nextChanger = None
-
- def setImage(self, filename):
- self._setImage(filename)
- if self.nextChanger is not None:
- self.nextChange.changeTo(filename)
-class __WMakerChanger(__BaseChanger):
+ def set_image(self, filename):
+ raise NotImplementedError()
+
+class WMakerChanger(BaseChanger):
+ name = "WindowMaker"
_ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
_ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
- def _removeOldImageCache(self):
+ def remove_old_image_cache(self):
"""Cleans up any old temp images"""
if not os.path.isdir(self._ConvertedWallpaperLocation):
os.mkdir(self._ConvertedWallpaperLocation)
"""Cleans up any old temp images"""
if not os.path.isdir(self._ConvertedWallpaperLocation):
os.mkdir(self._ConvertedWallpaperLocation)
for dirname in dirnames:
os.unlink(os.path.join(fullpath, dirname))
for dirname in dirnames:
os.unlink(os.path.join(fullpath, dirname))
- def _convertImageFormat(self, file):
+ def convert_image_format(self, file):
"""Convert the image to a png, and store it in a local place"""
"""Convert the image to a png, and store it in a local place"""
- self._removeOldImageCache()
+ 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]
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)
+ debug("""Convert command: '"%s"'""" % '" "'.join(cmd))
return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
- def _setImage(self, file):
- file, convert_status = self._convertImageFormat(file)
+ def set_image(self, file):
+ file, convert_status = self.convert_image_format(file)
if convert_status:
debug('Convert failed')
cmd = ["wmsetbg",
if convert_status:
debug('Convert failed')
cmd = ["wmsetbg",
- "-b", self.backgroundColour, # Sets the background colour to be what the user specified
+ "-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
"-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
if self.permanent:
cmd += ["-u"] # update the wmaker database
cmd += [file]
if self.permanent:
cmd += ["-u"] # update the wmaker database
cmd += [file]
- debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd), DEBUG_LEVEL_DEBUG)
+ debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd))
return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
-class __OSXChanger(__BaseChanger):
+class OSXChanger(BaseChanger):
+ name = "Mac OS X"
_ConvertedWallpaperLocation = '/tmp/wallpapers/'
_DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
_ConvertedWallpaperLocation = '/tmp/wallpapers/'
_DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
- def _removeOldImageCache(self):
+ def remove_old_image_cache(self):
"""Cleans up any old temp images"""
if not os.path.isdir(self._ConvertedWallpaperLocation):
os.mkdir(self._ConvertedWallpaperLocation)
"""Cleans up any old temp images"""
if not os.path.isdir(self._ConvertedWallpaperLocation):
os.mkdir(self._ConvertedWallpaperLocation)
for dirname in dirnames:
os.unlink(os.path.join(fullpath, dirname))
for dirname in dirnames:
os.unlink(os.path.join(fullpath, dirname))
- def _convertImageFormat(self, file):
+ def convert_image_format(self, file):
"""Convert the image to a png, and store it in a local place"""
"""Convert the image to a png, and store it in a local place"""
- self._removeOldImageCache()
+ self.remove_old_image_cache()
output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
try:
import PIL, PIL.Image
output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
try:
import PIL, PIL.Image
shutil.copyfile(file, output_name)
return output_name, True
shutil.copyfile(file, output_name)
return output_name, True
- def _fixDesktopPList(self):
+ def fix_desktop_plist(self):
"""Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
try:
import Foundation
"""Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
try:
import Foundation
- desktopPList = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
+ desktop_plist = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
# Remove all but the 'default' entry
# Remove all but the 'default' entry
- for k in desktopPList['Background'].keys():
+ for k in desktop_plist['Background'].keys():
if k == 'default':
continue
if k == 'default':
continue
- desktopPList['Background'].removeObjectForKey_(k)
+ desktop_plist['Background'].removeObjectForKey_(k)
# Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
# Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
- desktopPList.writeToFile_atomically_(self._DesktopPlistLocation, True)
+ desktop_plist.writeToFile_atomically_(self._DesktopPlistLocation, True)
- debug('Could not import the Foundation module, you may have problems with dual screens', DEBUG_LEVEL_MEDIUM)
+ debug('Could not import the Foundation module, you may have problems with dual screens')
- def _setImage(self, file):
- output_name, ret = self._convertImageFormat(file)
+ def set_image(self, file):
+ output_name, ret = self.convert_image_format(file)
if not ret:
debug("Convert failed")
return False
if not ret:
debug("Convert failed")
return False
- self._fixDesktopPList()
+ self.fix_desktop_plist()
cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
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]
return not commands.getstatusoutput(cmd)[0]
-class __GnomeChanger(__BaseChanger):
- def _setImage(self, file):
+class GnomeChanger(BaseChanger):
+ name = "Gnome"
+ def set_image(self, file):
cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', 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()
+ debug(cmd)
+ return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
-class __KDEChanger(__BaseChanger):
- def _setImage(self, file):
+class KDEChanger(BaseChanger):
+ name = "KDE"
+ def set_image(self, file):
cmds = []
for group in ('Desktop0', 'Desktop0Screen0'):
base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
cmds = []
for group in ('Desktop0', 'Desktop0Screen0'):
base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
for cmd in cmds:
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:
if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
+ return False
+
+ return True
+
+
+def main(filename):
+ import logging
+ logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
+ init()
+ set_image(filename)
+
+if __name__ == "__main__":
+ try:
+ filename = sys.argv[1]
+ except:
+ print >>sys.stderr, "Usage: %s filename" % sys.argv[0]
+ sys.exit(1)
+
+ main(filename)