2 # Copyright 2008 Greg Darke <greg@tsukasa.net.au>
3 # Copyright 2008 James Bunton <jamesbunton@fastmail.fm>
4 # Licensed for distribution under the GPL version 2, check COPYING for details
5 # This is a cross platform/cross window manager way to change your wallpaper
7 import commands
, sys
, os
, os
.path
, subprocess
, time
8 from logging
import debug
, info
, warning
10 __all__
= ("init", "set_image")
15 def set_image(filename
):
16 for changer
in changers
:
17 if not changer
.set_image(filename
):
18 warning("Failed to set background: wallchanger.set_image(%s), changer=%s" % (filename
, changer
))
20 def init(*args
, **kwargs
):
21 """Desktop Changer factory"""
23 debug("Testing for OSX (NonX11)")
24 if commands
.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
25 changers
.append(OSXChanger(*args
, **kwargs
))
27 if 'DISPLAY' not in os
.environ
or os
.environ
['DISPLAY'].startswith('/tmp/launch'):
31 if os
.uname()[0] == 'Darwin':
32 # Try to detect if the X11 server is running on OSX
33 if commands
.getstatusoutput("ps ax -o command|grep -q '/.*X11 .* %s'" % os
.environ
['DISPLAY'])[0] != 0:
34 # X11 is not running for this display
37 debug("Testing for KDE")
38 if commands
.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
39 changers
.append(KDEChanger(*args
, **kwargs
))
41 debug("Testing for Gnome")
42 if commands
.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
43 changers
.append(GnomeChanger(*args
, **kwargs
))
45 debug("Testing for WMaker")
46 if commands
.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
47 changers
.append(WMakerChanger(*args
, **kwargs
))
49 if len(changers
) == 0:
50 raise Exception("Unknown window manager")
53 class BaseChanger(object):
55 def __init__(self
, background_color
='black', permanent
=False):
56 info('Determined the window manager is "%s"' % self
.name
)
57 self
.background_color
= background_color
58 self
.permanent
= permanent
60 def set_image(self
, filename
):
61 raise NotImplementedError()
63 class WMakerChanger(BaseChanger
):
65 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
66 def remove_old_image_cache(self
):
67 """Cleans up any old temp images"""
68 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
69 os
.mkdir(self
._ConvertedWallpaperLocation
)
70 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
71 for filename
in filenames
:
72 os
.unlink(os
.path
.join(fullpath
, filename
))
73 for dirname
in dirnames
:
74 os
.unlink(os
.path
.join(fullpath
, dirname
))
76 def convert_image_format(self
, file):
77 """Convert the image to a png, and store it in a local place"""
78 self
.remove_old_image_cache()
79 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
80 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name
]
81 debug("""Convert command: '"%s"'""" % '" "'.join(cmd
))
82 return output_name
, subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
84 def set_image(self
, file):
85 file, convert_status
= self
.convert_image_format(file)
87 debug('Convert failed')
89 "-b", self
.background_color
, # Sets the background colour to be what the user specified
90 "-S", # 'Smooth' (WTF?)
91 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
92 ### "-a", # scale the image, keeping the aspect ratio
93 "-u", # Force this to be the default background
97 cmd
+= ["-u"] # update the wmaker database
99 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd
))
100 return not subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
102 class OSXChanger(BaseChanger
):
104 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
105 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
107 def remove_old_image_cache(self
):
108 """Cleans up any old temp images"""
109 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
110 os
.mkdir(self
._ConvertedWallpaperLocation
)
111 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
112 for filename
in filenames
:
113 os
.unlink(os
.path
.join(fullpath
, filename
))
114 for dirname
in dirnames
:
115 os
.unlink(os
.path
.join(fullpath
, dirname
))
117 def convert_image_format(self
, file):
118 """Convert the image to a png, and store it in a local place"""
119 self
.remove_old_image_cache()
120 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
122 import PIL
, PIL
.Image
123 img
= PIL
.Image
.open(file)
124 img
.save(output_name
, "PNG")
125 return output_name
, True
127 debug('Could not load PIL, going to try just copying the image')
129 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(file))
130 shutil
.copyfile(file, output_name
)
131 return output_name
, True
133 def fix_desktop_plist(self
):
134 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
137 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
138 # Remove all but the 'default' entry
139 for k
in desktop_plist
['Background'].keys():
142 desktop_plist
['Background'].removeObjectForKey_(k
)
143 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
144 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
146 debug('Could not import the Foundation module, you may have problems with dual screens')
148 def set_image(self
, file):
149 output_name
, ret
= self
.convert_image_format(file)
151 debug("Convert failed")
153 self
.fix_desktop_plist()
154 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
156 return not commands
.getstatusoutput(cmd
)[0]
158 class GnomeChanger(BaseChanger
):
160 def set_image(self
, file):
161 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
163 return not subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
165 class KDEChanger(BaseChanger
):
167 def set_image(self
, file):
169 for group
in ('Desktop0', 'Desktop0Screen0'):
170 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
171 cmds
.append(base
+ ['Wallpaper', file])
172 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
173 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
174 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
176 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
179 if subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait() != 0:
187 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
191 if __name__
== "__main__":
193 filename
= sys
.argv
[1]
195 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]