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
)
26 return commands
.getstatusoutput(cmd
)[0] == 0
28 def init(*args
, **kwargs
):
29 """Desktop Changer factory"""
31 if sys
.platform
== "win32":
32 changers
.append(WIN32Changer(*args
, **kwargs
))
35 logging
.debug("Testing for OSX (NonX11)")
36 if check_cmd("ps ax -o command -c|grep -q WindowServer"):
37 changers
.append(OSXChanger(*args
, **kwargs
))
39 if 'DISPLAY' not in os
.environ
or os
.environ
['DISPLAY'].startswith('/tmp/launch'):
43 if os
.uname()[0] == 'Darwin':
44 # Try to detect if the X11 server is running on OSX
45 if check_cmd("ps ax -o command|grep -q '^/.*X11 .* %s'" % os
.environ
['DISPLAY']):
46 # X11 is not running for this display
49 logging
.debug("Testing for KDE")
50 if check_cmd("xwininfo -name 'KDE Desktop'"):
51 changers
.append(KDEChanger(*args
, **kwargs
))
53 logging
.debug("Testing for Gnome")
54 if check_cmd("xwininfo -name 'gnome-settings-daemon'"):
55 if check_cmd("gsettings get org.gnome.desktop.background picture-uri"):
56 changers
.append(Gnome3Changer(*args
, **kwargs
))
58 changers
.append(Gnome2Changer(*args
, **kwargs
))
60 logging
.debug("Testing for WMaker")
61 if check_cmd("xlsclients | grep -qi wmaker"):
62 changers
.append(WMakerChanger(*args
, **kwargs
))
64 if len(changers
) == 0:
65 raise Exception("Unknown window manager")
68 class BaseChanger(object):
70 def __init__(self
, background_color
='black', permanent
=False, convert
=False):
71 logging
.info('Determined the window manager is "%s"', self
.name
)
72 self
.background_color
= background_color
73 self
.permanent
= permanent
74 self
.convert
= convert
77 def _exec_cmd(self
, cmd
):
79 return subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
82 # A simple implementation of subprocess for python2.4
83 def _exec_cmd(self
, cmd
):
84 """Runs a program given in cmd"""
85 return os
.spawnvp(os
.P_WAIT
, cmd
[0], cmd
)
87 def set_image(self
, filename
):
88 raise NotImplementedError()
90 def convert_image_format(self
, filename
, format
='BMP', allowAlpha
=False, extension
='.bmp'):
91 """Convert the image to another format, and store it in a local place"""
92 if not os
.path
.exists(filename
):
93 logger
.warn('The input file "%s" does not exist, so it will not be converted', filename
)
94 return filename
, False
96 logger
.warn('PIL could not be found, not converting image format')
97 return filename
, False
99 self
.remove_old_image_cache()
100 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s%s' % (time
.time(), extension
))
101 img
= PIL
.Image
.open(filename
)
103 # Remove the alpha channel if the user doens't want it
104 if not allowAlpha
and img
.mode
== 'RGBA':
105 img
= img
.convert('RGB')
106 img
.save(output_name
, format
)
108 return output_name
, True
111 class WMakerChanger(BaseChanger
):
113 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
114 def remove_old_image_cache(self
):
115 """Cleans up any old temp images"""
116 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
117 os
.mkdir(self
._ConvertedWallpaperLocation
)
118 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
119 for filename
in filenames
:
120 os
.unlink(os
.path
.join(fullpath
, filename
))
121 for dirname
in dirnames
:
122 os
.unlink(os
.path
.join(fullpath
, dirname
))
124 def convert_image_format(self
, filename
):
125 """Convert the image to a png, and store it in a local place"""
126 self
.remove_old_image_cache()
127 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
128 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', filename
, output_name
]
129 logging
.debug("""Convert command: '"%s"'""", '" "'.join(cmd
))
130 return output_name
, self
._exec
_cmd
(cmd
)
132 def set_image(self
, filename
):
134 filename
, convert_status
= self
.convert_image_format(filename
)
136 logging
.debug('Convert failed')
138 "-b", self
.background_color
, # Sets the background colour to be what the user specified
139 "-S", # 'Smooth' (WTF?)
140 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
141 ### "-a", # scale the image, keeping the aspect ratio
142 "-u", # Force this to be the default background
146 cmd
+= ["-u"] # update the wmaker database
148 logging
.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd
))
149 return not self
._exec
_cmd
(cmd
)
151 class OSXChanger(BaseChanger
):
153 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
154 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
156 def __init__(self
, *args
, **kwargs
):
157 BaseChanger
.__init
__(self
, *args
, **kwargs
)
159 def remove_old_image_cache(self
):
160 """Cleans up any old temp images"""
161 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
162 os
.mkdir(self
._ConvertedWallpaperLocation
)
163 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
164 for filename
in filenames
:
165 os
.unlink(os
.path
.join(fullpath
, filename
))
166 for dirname
in dirnames
:
167 os
.unlink(os
.path
.join(fullpath
, dirname
))
169 def convert_image_format(self
, filename
):
170 """Convert the image to a png, and store it in a local place"""
171 self
.remove_old_image_cache()
172 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
174 return super(OSXChanger
, self
).convert_image_format(filename
, format
='PNG', extension
='.png')
176 logging
.debug('Could not load PIL, going to try just copying the image')
178 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(filename
))
179 shutil
.copyfile(filename
, output_name
)
180 return output_name
, True
182 def fix_desktop_plist(self
):
183 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
186 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
187 # Remove all but the 'default' entry
188 for k
in desktop_plist
['Background'].keys():
191 desktop_plist
['Background'].removeObjectForKey_(k
)
192 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
193 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
195 logging
.debug('Could not import the Foundation module, you may have problems with dual screens')
197 def set_image(self
, filename
):
198 self
.fix_desktop_plist()
200 filename
, ret
= self
.convert_image_format(filename
)
202 logging
.debug("Convert failed")
204 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
206 return not commands
.getstatusoutput(cmd
)[0]
208 class WIN32Changer(BaseChanger
):
210 _ConvertedWallpaperLocation
= os
.path
.join(os
.environ
.get('APPDATA', os
.path
.expanduser('~')), 'wallchanger')
212 def __init__(self
, *args
, **kwargs
):
213 BaseChanger
.__init
__(self
, *args
, **kwargs
)
215 logging
.warn('Running on windows, but convert is not set')
217 def remove_old_image_cache(self
):
218 """Cleans up any old temp images"""
219 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
220 os
.mkdir(self
._ConvertedWallpaperLocation
)
221 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
222 for filename
in filenames
:
223 os
.unlink(os
.path
.join(fullpath
, filename
))
224 for dirname
in dirnames
:
225 os
.unlink(os
.path
.join(fullpath
, dirname
))
227 def set_image(self
, filename
):
229 user32
= ctypes
.windll
.user32
231 # Taken from the Platform SDK
232 SPI_SETDESKWALLPAPER
= 20
233 SPIF_SENDWININICHANGE
= 2
236 filename
, ret
= self
.convert_image_format(filename
)
238 logging
.debug("Convert failed")
241 # Parameters for SystemParametersInfoA are:
242 # (UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni)
243 user32
.SystemParametersInfoA(
244 SPI_SETDESKWALLPAPER
,
247 SPIF_SENDWININICHANGE
,
251 class Gnome2Changer(BaseChanger
):
253 def set_image(self
, filename
):
254 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', filename
]
256 return not self
._exec
_cmd
(cmd
)
258 class Gnome3Changer(BaseChanger
):
260 def set_image(self
, filename
):
261 cmd
= ['gsettings', 'set', 'org.gnome.desktop.background', 'picture-uri', 'file://'+filename
]
263 return not self
._exec
_cmd
(cmd
)
265 class KDEChanger(BaseChanger
):
267 def set_image(self
, filename
):
269 for group
in ('Desktop0', 'Desktop0Screen0'):
270 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
271 cmds
.append(base
+ ['Wallpaper', filename
])
272 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
273 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
274 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
276 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
279 if self
._exec
_cmd
(cmd
) != 0:
286 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
290 if __name__
== "__main__":
292 filename
= sys
.argv
[1]
294 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]