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
14 __all__
= ("init", "set_image")
19 def set_image(filename
):
20 logging
.info("Setting image: %s", filename
)
21 for changer
in changers
:
22 if not changer
.set_image(filename
):
23 logging
.warning("Failed to set background: wallchanger.set_image(%s), changer=%s", filename
, changer
)
25 def init(*args
, **kwargs
):
26 """Desktop Changer factory"""
28 if sys
.platform
== "win32":
29 changers
.append(WIN32Changer(*args
, **kwargs
))
32 logging
.debug("Testing for OSX (NonX11)")
33 if commands
.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
34 changers
.append(OSXChanger(*args
, **kwargs
))
36 if 'DISPLAY' not in os
.environ
or os
.environ
['DISPLAY'].startswith('/tmp/launch'):
40 if os
.uname()[0] == 'Darwin':
41 # Try to detect if the X11 server is running on OSX
42 if commands
.getstatusoutput("ps ax -o command|grep -q '^/.*X11 .* %s'" % os
.environ
['DISPLAY'])[0] != 0:
43 # X11 is not running for this display
46 logging
.debug("Testing for KDE")
47 if commands
.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
48 changers
.append(KDEChanger(*args
, **kwargs
))
50 logging
.debug("Testing for Unity")
51 if commands
.getstatusoutput("xlsclients | grep -qi unity")[0] == 0:
52 changers
.append(UnityChanger(*args
, **kwargs
))
54 logging
.debug("Testing for Gnome")
55 if commands
.getstatusoutput("xwininfo -name 'gnome-settings-daemon'")[0] == 0:
56 changers
.append(GnomeChanger(*args
, **kwargs
))
58 logging
.debug("Testing for WMaker")
59 if commands
.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
60 changers
.append(WMakerChanger(*args
, **kwargs
))
62 if len(changers
) == 0:
63 raise Exception("Unknown window manager")
66 class BaseChanger(object):
68 def __init__(self
, background_color
='black', permanent
=False, convert
=False):
69 logging
.info('Determined the window manager is "%s"', self
.name
)
70 self
.background_color
= background_color
71 self
.permanent
= permanent
72 self
.convert
= convert
77 self
._runProgram
= self
._runProgram
_command
79 self
._runProgram
= self
._runProgram
_subprocess
81 def _runProgram_subprocess(self
, cmd
):
83 return subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
85 # A simple implementation of subprocess for python2.4
86 def _runProgram_command(self
, cmd
):
87 """Runs a program given in cmd"""
88 return os
.spawnvp(os
.P_WAIT
, cmd
[0], cmd
)
90 def set_image(self
, filename
):
91 raise NotImplementedError()
93 def convert_image_format(self
, filename
, format
='BMP', allowAlpha
=False, extension
='.bmp'):
94 """Convert the image to another format, and store it in a local place"""
95 if not os
.path
.exists(filename
):
96 logger
.warn('The input file "%s" does not exist, so it will not be converted', filename
)
97 return filename
, False
99 logger
.warn('PIL could not be found, not converting image format')
100 return filename
, False
102 self
.remove_old_image_cache()
103 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s%s' % (time
.time(), extension
))
104 img
= PIL
.Image
.open(filename
)
106 # Remove the alpha channel if the user doens't want it
107 if not allowAlpha
and img
.mode
== 'RGBA':
108 img
= img
.convert('RGB')
109 img
.save(output_name
, format
)
111 return output_name
, True
114 class WMakerChanger(BaseChanger
):
116 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
117 def remove_old_image_cache(self
):
118 """Cleans up any old temp images"""
119 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
120 os
.mkdir(self
._ConvertedWallpaperLocation
)
121 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
122 for filename
in filenames
:
123 os
.unlink(os
.path
.join(fullpath
, filename
))
124 for dirname
in dirnames
:
125 os
.unlink(os
.path
.join(fullpath
, dirname
))
127 def convert_image_format(self
, file):
128 """Convert the image to a png, and store it in a local place"""
129 self
.remove_old_image_cache()
130 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
131 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name
]
132 logging
.debug("""Convert command: '"%s"'""", '" "'.join(cmd
))
133 return output_name
, self
._runProgram
(cmd
)
135 def set_image(self
, file):
137 file, convert_status
= self
.convert_image_format(file)
139 logging
.debug('Convert failed')
141 "-b", self
.background_color
, # Sets the background colour to be what the user specified
142 "-S", # 'Smooth' (WTF?)
143 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
144 ### "-a", # scale the image, keeping the aspect ratio
145 "-u", # Force this to be the default background
149 cmd
+= ["-u"] # update the wmaker database
151 logging
.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd
))
152 return not self
._runProgram
(cmd
)
154 class OSXChanger(BaseChanger
):
156 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
157 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
159 def __init__(self
, *args
, **kwargs
):
160 BaseChanger
.__init
__(self
, *args
, **kwargs
)
162 def remove_old_image_cache(self
):
163 """Cleans up any old temp images"""
164 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
165 os
.mkdir(self
._ConvertedWallpaperLocation
)
166 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
167 for filename
in filenames
:
168 os
.unlink(os
.path
.join(fullpath
, filename
))
169 for dirname
in dirnames
:
170 os
.unlink(os
.path
.join(fullpath
, dirname
))
172 def convert_image_format(self
, file):
173 """Convert the image to a png, and store it in a local place"""
174 self
.remove_old_image_cache()
175 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
177 return super(OSXChanger
, self
).convert_image_format(file, format
='PNG', extension
='.png')
179 logging
.debug('Could not load PIL, going to try just copying the image')
181 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(file))
182 shutil
.copyfile(file, output_name
)
183 return output_name
, True
185 def fix_desktop_plist(self
):
186 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
189 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
190 # Remove all but the 'default' entry
191 for k
in desktop_plist
['Background'].keys():
194 desktop_plist
['Background'].removeObjectForKey_(k
)
195 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
196 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
198 logging
.debug('Could not import the Foundation module, you may have problems with dual screens')
200 def set_image(self
, filename
):
201 self
.fix_desktop_plist()
203 filename
, ret
= self
.convert_image_format(filename
)
205 logging
.debug("Convert failed")
207 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
209 return not commands
.getstatusoutput(cmd
)[0]
211 class WIN32Changer(BaseChanger
):
213 _ConvertedWallpaperLocation
= os
.path
.join(os
.environ
.get('APPDATA', os
.path
.expanduser('~')), 'wallchanger')
215 def __init__(self
, *args
, **kwargs
):
216 BaseChanger
.__init
__(self
, *args
, **kwargs
)
218 logging
.warn('Running on windows, but convert is not set')
220 def remove_old_image_cache(self
):
221 """Cleans up any old temp images"""
222 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
223 os
.mkdir(self
._ConvertedWallpaperLocation
)
224 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
225 for filename
in filenames
:
226 os
.unlink(os
.path
.join(fullpath
, filename
))
227 for dirname
in dirnames
:
228 os
.unlink(os
.path
.join(fullpath
, dirname
))
230 def set_image(self
, filename
):
232 user32
= ctypes
.windll
.user32
234 # Taken from the Platform SDK
235 SPI_SETDESKWALLPAPER
= 20
236 SPIF_SENDWININICHANGE
= 2
239 filename
, ret
= self
.convert_image_format(filename
)
241 logging
.debug("Convert failed")
244 # Parameters for SystemParametersInfoA are:
245 # (UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni)
246 user32
.SystemParametersInfoA(
247 SPI_SETDESKWALLPAPER
,
250 SPIF_SENDWININICHANGE
,
254 class GnomeChanger(BaseChanger
):
256 def set_image(self
, file):
257 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
259 return not self
._runProgram
(cmd
)
261 class UnityChanger(BaseChanger
):
263 def set_image(self
, file):
264 cmd
= ['gsettings', 'set', 'org.gnome.desktop.background', 'picture-uri', 'file://'+file]
266 return not self
._runProgram
(cmd
)
268 class KDEChanger(BaseChanger
):
270 def set_image(self
, file):
272 for group
in ('Desktop0', 'Desktop0Screen0'):
273 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
274 cmds
.append(base
+ ['Wallpaper', file])
275 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
276 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
277 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
279 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
282 if self
._runProgram
(cmd
) != 0:
289 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
293 if __name__
== "__main__":
295 filename
= sys
.argv
[1]
297 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]