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 Gnome")
51 if commands
.getstatusoutput("xwininfo -name 'gnome-settings-daemon'")[0] == 0:
52 changers
.append(GnomeChanger(*args
, **kwargs
))
54 logging
.debug("Testing for WMaker")
55 if commands
.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
56 changers
.append(WMakerChanger(*args
, **kwargs
))
58 if len(changers
) == 0:
59 raise Exception("Unknown window manager")
62 class BaseChanger(object):
64 def __init__(self
, background_color
='black', permanent
=False, convert
=False):
65 logging
.info('Determined the window manager is "%s"', self
.name
)
66 self
.background_color
= background_color
67 self
.permanent
= permanent
68 self
.convert
= convert
73 self
._runProgram
= self
._runProgram
_command
75 self
._runProgram
= self
._runProgram
_subprocess
77 def _runProgram_subprocess(self
, cmd
):
79 return subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
81 # A simple implementation of subprocess for python2.4
82 def _runProgram_command(self
, cmd
):
83 """Runs a program given in cmd"""
84 return os
.spawnvp(os
.P_WAIT
, cmd
[0], cmd
)
86 def set_image(self
, filename
):
87 raise NotImplementedError()
89 def convert_image_format(self
, filename
, format
='BMP', allowAlpha
=False, extension
='.bmp'):
90 """Convert the image to another format, and store it in a local place"""
91 if not os
.path
.exists(filename
):
92 logger
.warn('The input file "%s" does not exist, so it will not be converted', filename
)
93 return filename
, False
95 logger
.warn('PIL could not be found, not converting image format')
96 return filename
, False
98 self
.remove_old_image_cache()
99 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s%s' % (time
.time(), extension
))
100 img
= PIL
.Image
.open(filename
)
102 # Remove the alpha channel if the user doens't want it
103 if not allowAlpha
and img
.mode
== 'RGBA':
104 img
= img
.convert('RGB')
105 img
.save(output_name
, format
)
107 return output_name
, True
110 class WMakerChanger(BaseChanger
):
112 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
113 def remove_old_image_cache(self
):
114 """Cleans up any old temp images"""
115 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
116 os
.mkdir(self
._ConvertedWallpaperLocation
)
117 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
118 for filename
in filenames
:
119 os
.unlink(os
.path
.join(fullpath
, filename
))
120 for dirname
in dirnames
:
121 os
.unlink(os
.path
.join(fullpath
, dirname
))
123 def convert_image_format(self
, file):
124 """Convert the image to a png, and store it in a local place"""
125 self
.remove_old_image_cache()
126 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
127 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name
]
128 logging
.debug("""Convert command: '"%s"'""", '" "'.join(cmd
))
129 return output_name
, self
._runProgram
(cmd
)
131 def set_image(self
, file):
133 file, convert_status
= self
.convert_image_format(file)
135 logging
.debug('Convert failed')
137 "-b", self
.background_color
, # Sets the background colour to be what the user specified
138 "-S", # 'Smooth' (WTF?)
139 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
140 ### "-a", # scale the image, keeping the aspect ratio
141 "-u", # Force this to be the default background
145 cmd
+= ["-u"] # update the wmaker database
147 logging
.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd
))
148 return not self
._runProgram
(cmd
)
150 class OSXChanger(BaseChanger
):
152 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
153 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
155 def __init__(self
, *args
, **kwargs
):
156 BaseChanger
.__init
__(self
, *args
, **kwargs
)
158 def remove_old_image_cache(self
):
159 """Cleans up any old temp images"""
160 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
161 os
.mkdir(self
._ConvertedWallpaperLocation
)
162 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
163 for filename
in filenames
:
164 os
.unlink(os
.path
.join(fullpath
, filename
))
165 for dirname
in dirnames
:
166 os
.unlink(os
.path
.join(fullpath
, dirname
))
168 def convert_image_format(self
, file):
169 """Convert the image to a png, and store it in a local place"""
170 self
.remove_old_image_cache()
171 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
173 return super(OSXChanger
, self
).convert_image_format(file, format
='PNG', extension
='.png')
175 logging
.debug('Could not load PIL, going to try just copying the image')
177 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(file))
178 shutil
.copyfile(file, output_name
)
179 return output_name
, True
181 def fix_desktop_plist(self
):
182 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
185 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
186 # Remove all but the 'default' entry
187 for k
in desktop_plist
['Background'].keys():
190 desktop_plist
['Background'].removeObjectForKey_(k
)
191 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
192 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
194 logging
.debug('Could not import the Foundation module, you may have problems with dual screens')
196 def set_image(self
, filename
):
197 self
.fix_desktop_plist()
199 filename
, ret
= self
.convert_image_format(filename
)
201 logging
.debug("Convert failed")
203 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
205 return not commands
.getstatusoutput(cmd
)[0]
207 class WIN32Changer(BaseChanger
):
209 _ConvertedWallpaperLocation
= os
.path
.join(os
.environ
.get('APPDATA', os
.path
.expanduser('~')), 'wallchanger')
211 def __init__(self
, *args
, **kwargs
):
212 BaseChanger
.__init
__(self
, *args
, **kwargs
)
214 logging
.warn('Running on windows, but convert is not set')
216 def remove_old_image_cache(self
):
217 """Cleans up any old temp images"""
218 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
219 os
.mkdir(self
._ConvertedWallpaperLocation
)
220 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
221 for filename
in filenames
:
222 os
.unlink(os
.path
.join(fullpath
, filename
))
223 for dirname
in dirnames
:
224 os
.unlink(os
.path
.join(fullpath
, dirname
))
226 def set_image(self
, filename
):
228 user32
= ctypes
.windll
.user32
230 # Taken from the Platform SDK
231 SPI_SETDESKWALLPAPER
= 20
232 SPIF_SENDWININICHANGE
= 2
235 filename
, ret
= self
.convert_image_format(filename
)
237 logging
.debug("Convert failed")
240 # Parameters for SystemParametersInfoA are:
241 # (UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni)
242 user32
.SystemParametersInfoA(
243 SPI_SETDESKWALLPAPER
,
246 SPIF_SENDWININICHANGE
,
250 class GnomeChanger(BaseChanger
):
252 def set_image(self
, file):
253 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
255 return not self
._runProgram
(cmd
)
257 class KDEChanger(BaseChanger
):
259 def set_image(self
, file):
261 for group
in ('Desktop0', 'Desktop0Screen0'):
262 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
263 cmds
.append(base
+ ['Wallpaper', file])
264 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
265 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
266 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
268 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
271 if self
._runProgram
(cmd
) != 0:
278 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
282 if __name__
== "__main__":
284 filename
= sys
.argv
[1]
286 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]