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
, time
10 __all__
= ("init", "set_image")
15 def set_image(filename
):
16 logging
.info("Setting image: %s", filename
)
17 for changer
in changers
:
18 if not changer
.set_image(filename
):
19 logging
.warning("Failed to set background: wallchanger.set_image(%s), changer=%s", filename
, changer
)
21 def init(*args
, **kwargs
):
22 """Desktop Changer factory"""
24 if sys
.platform
== "win32":
25 changers
.append(WIN32Changer(*args
, **kwargs
))
28 logging
.debug("Testing for OSX (NonX11)")
29 if commands
.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
30 changers
.append(OSXChanger(*args
, **kwargs
))
32 if 'DISPLAY' not in os
.environ
or os
.environ
['DISPLAY'].startswith('/tmp/launch'):
36 if os
.uname()[0] == 'Darwin':
37 # Try to detect if the X11 server is running on OSX
38 if commands
.getstatusoutput("ps ax -o command|grep -q '^/.*X11 .* %s'" % os
.environ
['DISPLAY'])[0] != 0:
39 # X11 is not running for this display
42 logging
.debug("Testing for KDE")
43 if commands
.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
44 changers
.append(KDEChanger(*args
, **kwargs
))
46 logging
.debug("Testing for Gnome")
47 if commands
.getstatusoutput("xwininfo -name 'gnome-settings-daemon'")[0] == 0:
48 changers
.append(GnomeChanger(*args
, **kwargs
))
50 logging
.debug("Testing for WMaker")
51 if commands
.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
52 changers
.append(WMakerChanger(*args
, **kwargs
))
54 if len(changers
) == 0:
55 raise Exception("Unknown window manager")
58 class BaseChanger(object):
60 def __init__(self
, background_color
='black', permanent
=False, convert
=False):
61 logging
.info('Determined the window manager is "%s"', self
.name
)
62 self
.background_color
= background_color
63 self
.permanent
= permanent
64 self
.convert
= convert
69 self
._runProgram
= self
._runProgram
_command
71 self
._runProgram
= self
._runProgram
_subprocess
73 def _runProgram_subprocess(self
, cmd
):
75 return subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
77 # A simple implementation of subprocess for python2.4
78 def _runProgram_command(self
, cmd
):
79 """Runs a program given in cmd"""
80 return os
.spawnvp(os
.P_WAIT
, cmd
[0], cmd
)
82 def set_image(self
, filename
):
83 raise NotImplementedError()
85 def convert_image_format(self
, filename
, format
='BMP', allowAlpha
=False, extension
='.bmp'):
86 """Convert the image to another format, and store it in a local place"""
89 self
.remove_old_image_cache()
90 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s%s' % (time
.time(), extension
))
91 img
= PIL
.Image
.open(filename
)
93 # Remove the alpha channel if the user doens't want it
94 if not allowAlpha
and img
.mode
== 'RGBA':
95 img
= img
.convert('RGB')
96 img
.save(output_name
, format
)
98 return output_name
, True
101 class WMakerChanger(BaseChanger
):
103 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
104 def remove_old_image_cache(self
):
105 """Cleans up any old temp images"""
106 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
107 os
.mkdir(self
._ConvertedWallpaperLocation
)
108 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
109 for filename
in filenames
:
110 os
.unlink(os
.path
.join(fullpath
, filename
))
111 for dirname
in dirnames
:
112 os
.unlink(os
.path
.join(fullpath
, dirname
))
114 def convert_image_format(self
, file):
115 """Convert the image to a png, and store it in a local place"""
116 self
.remove_old_image_cache()
117 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
118 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name
]
119 logging
.debug("""Convert command: '"%s"'""", '" "'.join(cmd
))
120 return output_name
, self
._runProgram
(cmd
)
122 def set_image(self
, file):
124 file, convert_status
= self
.convert_image_format(file)
126 logging
.debug('Convert failed')
128 "-b", self
.background_color
, # Sets the background colour to be what the user specified
129 "-S", # 'Smooth' (WTF?)
130 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
131 ### "-a", # scale the image, keeping the aspect ratio
132 "-u", # Force this to be the default background
136 cmd
+= ["-u"] # update the wmaker database
138 logging
.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd
))
139 return not self
._runProgram
(cmd
)
141 class OSXChanger(BaseChanger
):
143 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
144 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
146 def __init__(self
, *args
, **kwargs
):
147 BaseChanger
.__init
__(self
, *args
, **kwargs
)
149 def remove_old_image_cache(self
):
150 """Cleans up any old temp images"""
151 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
152 os
.mkdir(self
._ConvertedWallpaperLocation
)
153 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
154 for filename
in filenames
:
155 os
.unlink(os
.path
.join(fullpath
, filename
))
156 for dirname
in dirnames
:
157 os
.unlink(os
.path
.join(fullpath
, dirname
))
159 def convert_image_format(self
, file):
160 """Convert the image to a png, and store it in a local place"""
161 self
.remove_old_image_cache()
162 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
164 return super(OSXChanger
, self
).convert_image_format(file, format
='PNG', extension
='.png')
166 logging
.debug('Could not load PIL, going to try just copying the image')
168 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(file))
169 shutil
.copyfile(file, output_name
)
170 return output_name
, True
172 def fix_desktop_plist(self
):
173 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
176 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
177 # Remove all but the 'default' entry
178 for k
in desktop_plist
['Background'].keys():
181 desktop_plist
['Background'].removeObjectForKey_(k
)
182 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
183 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
185 logging
.debug('Could not import the Foundation module, you may have problems with dual screens')
187 def set_image(self
, filename
):
188 self
.fix_desktop_plist()
190 filename
, ret
= self
.convert_image_format(filename
)
192 logging
.debug("Convert failed")
194 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
196 return not commands
.getstatusoutput(cmd
)[0]
198 class WIN32Changer(BaseChanger
):
200 _ConvertedWallpaperLocation
= os
.path
.join(os
.environ
.get('APPDATA', os
.path
.expanduser('~')), 'wallchanger')
202 def __init__(self
, *args
, **kwargs
):
203 BaseChanger
.__init
__(self
, *args
, **kwargs
)
205 logging
.warn('Running on windows, but convert is not set')
207 def remove_old_image_cache(self
):
208 """Cleans up any old temp images"""
209 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
210 os
.mkdir(self
._ConvertedWallpaperLocation
)
211 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
212 for filename
in filenames
:
213 os
.unlink(os
.path
.join(fullpath
, filename
))
214 for dirname
in dirnames
:
215 os
.unlink(os
.path
.join(fullpath
, dirname
))
217 def set_image(self
, filename
):
219 user32
= ctypes
.windll
.user32
221 # Taken from the Platform SDK
222 SPI_SETDESKWALLPAPER
= 20
223 SPIF_SENDWININICHANGE
= 2
226 filename
, ret
= self
.convert_image_format(filename
)
228 logging
.debug("Convert failed")
231 # Parameters for SystemParametersInfoA are:
232 # (UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni)
233 user32
.SystemParametersInfoA(
234 SPI_SETDESKWALLPAPER
,
237 SPIF_SENDWININICHANGE
,
241 class GnomeChanger(BaseChanger
):
243 def set_image(self
, file):
244 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
246 return not self
._runProgram
(cmd
)
248 class KDEChanger(BaseChanger
):
250 def set_image(self
, file):
252 for group
in ('Desktop0', 'Desktop0Screen0'):
253 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
254 cmds
.append(base
+ ['Wallpaper', file])
255 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
256 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
257 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
259 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
262 if self
._runProgram
(cmd
) != 0:
269 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
273 if __name__
== "__main__":
275 filename
= sys
.argv
[1]
277 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]